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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65537ea
 
 
 
 
 
 
27e2970
65537ea
27e2970
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65537ea
27e2970
 
 
 
 
 
65537ea
 
 
27e2970
 
39839d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19a776a
39839d0
 
 
 
19a776a
39839d0
 
 
 
 
19a776a
39839d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19a776a
f2b4fca
 
 
 
 
 
39839d0
19a776a
39839d0
19a776a
 
39839d0
 
 
 
19a776a
39839d0
 
 
 
 
 
 
 
 
 
27e2970
 
 
 
 
39839d0
 
 
 
 
 
 
 
 
65537ea
27e2970
 
 
 
 
 
65537ea
39839d0
 
 
19a776a
39839d0
 
 
 
19a776a
39839d0
19a776a
39839d0
 
19a776a
 
39839d0
 
 
 
 
 
 
 
 
 
 
 
 
19a776a
39839d0
19a776a
39839d0
 
 
 
 
 
 
19a776a
f2b4fca
 
 
 
 
 
39839d0
 
 
 
 
 
 
 
 
 
 
 
 
 
f2b4fca
39839d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19a776a
39839d0
 
 
 
 
 
 
 
 
19a776a
 
39839d0
 
 
 
 
 
 
 
 
 
 
19a776a
 
39839d0
 
 
 
 
 
 
 
 
 
 
 
 
 
19a776a
 
39839d0
 
 
19a776a
39839d0
 
 
 
 
 
 
 
 
 
 
 
 
19a776a
39839d0
 
 
 
 
 
 
 
 
 
 
 
 
19a776a
39839d0
 
 
 
 
 
 
 
af38ab6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
import gc
import json
import os
import re
import threading
import time
from typing import Any, Literal

from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, Field, ValidationError


AGENT_ID = "defect-resolution-analyst"
DISPLAY_NAME = "Defect Resolution Intelligence Analyst"
AGENT_VERSION = "2.0"
MAX_AI_FINDINGS = 4
MAX_AI_CONTRACTS = 4

PRIORITY_ORDER = {
    "NONE": 0,
    "P3": 1,
    "P2": 2,
    "P1": 3,
}

RISK_ORDER = {
    "UNKNOWN": -1,
    "NONE": 0,
    "INFO": 1,
    "LOW": 2,
    "MEDIUM": 3,
    "HIGH": 4,
    "CRITICAL": 5,
}

MODEL_RESPONSE_SCHEMA = {
    "type": "object",
    "properties": {
        "p": {"type": "string", "enum": ["P1", "P2", "P3"]},
        "c": {"type": "string", "enum": ["HIGH", "MEDIUM", "LOW"]},
        "k": {"type": "boolean"},
        "kr": {"type": "string", "maxLength": 180},
        "x": {
            "type": "array",
            "minItems": 1,
            "maxItems": MAX_AI_CONTRACTS,
            "items": {
                "type": "object",
                "properties": {
                    "f": {
                        "type": "array",
                        "minItems": 1,
                        "maxItems": MAX_AI_FINDINGS,
                        "uniqueItems": True,
                        "items": {
                            "type": "string",
                            "minLength": 1,
                            "maxLength": 80,
                        },
                    },
                    "p": {"type": "string", "enum": ["P1", "P2", "P3"]},
                    "w": {"type": "string", "minLength": 8, "maxLength": 160},
                    "o": {"type": "string", "minLength": 8, "maxLength": 180},
                    "s": {"type": "string", "minLength": 8, "maxLength": 220},
                    "b": {"type": "string", "minLength": 6, "maxLength": 160},
                    "q": {"type": "string", "minLength": 6, "maxLength": 160},
                    "r": {"type": "string", "enum": ["L", "M", "H"]},
                    "v": {"type": "string", "minLength": 8, "maxLength": 220},
                },
                "required": ["f", "p", "w", "o", "s", "b", "q", "r", "v"],
                "additionalProperties": False,
            },
        },
    },
    "required": ["p", "c", "k", "kr", "x"],
    "additionalProperties": False,
}


def env_bool(name, default):
    value = os.getenv(name)
    if value is None:
        return bool(default)
    return value.strip().lower() in {"1", "true", "yes", "on"}


def clean_text(value, limit=800):
    text = " ".join(str(value or "").split()).strip()
    if len(text) <= limit:
        return text
    return text[: limit - 3].rstrip() + "..."


def normalize_list(value):
    if isinstance(value, list):
        return value
    if value is None:
        return []
    return [value]


def normalize_risk(value):
    risk = str(value or "UNKNOWN").upper()
    return risk if risk in RISK_ORDER else "UNKNOWN"


def highest_risk(*values):
    normalized = [normalize_risk(value) for value in values]
    return max(
        normalized,
        key=lambda value: RISK_ORDER.get(value, -1),
        default="UNKNOWN",
    )


def severity_priority(severity):
    severity = normalize_risk(severity)
    if severity in {"CRITICAL", "HIGH"}:
        return "P1"
    if severity == "MEDIUM":
        return "P2"
    return "P3"


class RepairRequest(BaseModel):
    model_config = ConfigDict(extra="ignore")

    project_type: str = Field(min_length=1, max_length=200)
    command: str = Field(default="", max_length=2000)
    success: bool
    exit_code: int | None = None
    stdout: str = Field(default="", max_length=16000)
    stderr: str = Field(default="", max_length=16000)
    failure_type: str | None = Field(default=None, max_length=200)
    help_message: str | None = Field(default=None, max_length=4000)
    runtime_evidence: dict[str, Any] | None = None
    runtime_analysis: dict[str, Any] | None = None
    source_review: dict[str, Any] | None = None


class ModelRepairContract(BaseModel):
    model_config = ConfigDict(extra="forbid", populate_by_name=True)

    finding_refs: list[str] = Field(alias="f", min_length=1, max_length=12)
    priority: Literal["P1", "P2", "P3"] = Field(alias="p")
    priority_reason: str = Field(alias="w", min_length=8, max_length=160)
    repair_objective: str = Field(alias="o", min_length=8, max_length=180)
    repair_strategy: str = Field(alias="s", min_length=8, max_length=220)
    change_boundary: str = Field(alias="b", min_length=6, max_length=160)
    protected_behavior: str = Field(alias="q", min_length=6, max_length=160)
    side_effect_risk_code: Literal["L", "M", "H"] = Field(alias="r")
    verification: str = Field(alias="v", min_length=8, max_length=220)

    @property
    def side_effect_risk(self):
        return {"L": "LOW", "M": "MEDIUM", "H": "HIGH"}[
            self.side_effect_risk_code
        ]


class ModelRepairPlan(BaseModel):
    model_config = ConfigDict(extra="forbid", populate_by_name=True)

    overall_priority: Literal["P1", "P2", "P3"] = Field(alias="p")
    confidence: Literal["HIGH", "MEDIUM", "LOW"] = Field(alias="c")
    current_knowledge_required: bool = Field(alias="k")
    current_knowledge_reason: str = Field(alias="kr", default="", max_length=180)
    contracts: list[ModelRepairContract] = Field(
        alias="x",
        min_length=1,
        max_length=MAX_AI_CONTRACTS,
    )


class StitchRepairContract(BaseModel):
    model_config = ConfigDict(extra="ignore")

    contract_id: str
    finding_refs: list[str]
    title: str
    priority: Literal["P1", "P2", "P3"]
    priority_reason: str
    repair_objective: str
    repair_strategy: str
    change_boundary: str
    protected_behavior: str
    side_effect_risk: Literal["LOW", "MEDIUM", "HIGH"]
    verification: str
    done_condition: str
    status: Literal["PENDING_VERIFICATION"] = "PENDING_VERIFICATION"


class RepairResponse(BaseModel):
    model_config = ConfigDict(extra="ignore")

    agent_id: str
    display_name: str
    agent_version: str
    agent: str
    mode: str
    model: str | None = None
    status: str
    overall_priority: str
    confidence: str
    repair_risk_level: str
    auto_apply: bool = False
    summary: str
    stitch_repair_contracts: list[StitchRepairContract] = Field(default_factory=list)
    current_knowledge_required: bool = False
    current_knowledge_reason: str | None = None
    next_action: str | None = None
    suggestions: list[str] = Field(default_factory=list)
    warnings: list[str] = Field(default_factory=list)
    limitations: list[str] = Field(default_factory=list)
    llm_metrics: dict[str, Any] | None = None
    llm_error: str | None = None


class ModelService:
    def __init__(self):
        self.model_repo = os.getenv(
            "HF_MODEL_REPO",
            "ibm-granite/granite-4.0-1b-GGUF",
        ).strip()
        self.model_file = os.getenv(
            "HF_MODEL_FILE",
            "granite-4.0-1b-Q4_K_M.gguf",
        ).strip()
        self.model_revision = os.getenv(
            "HF_MODEL_REVISION",
            "b27c2fe3f211b7f44e80fa620177aea371099aaa",
        ).strip()
        self.quantization = os.getenv(
            "MODEL_QUANTIZATION",
            "Q4_K_M",
        ).strip()
        self.primary_model = os.getenv(
            "HF_MODEL",
            f"{self.model_repo}:{self.quantization}",
        ).strip()
        self.cache_dir = os.getenv(
            "MODEL_CACHE_DIR",
            "/opt/huggingface/hub",
        ).strip()
        self.enabled = env_bool("LLM_ENABLED", True)
        self.local_files_only = env_bool("HF_LOCAL_FILES_ONLY", False)
        self.context_tokens = max(1024, int(os.getenv("MODEL_CONTEXT_TOKENS", "4096")))
        self.batch_tokens = max(
            64,
            min(
                self.context_tokens,
                int(os.getenv("MODEL_BATCH_TOKENS", "512")),
            ),
        )
        self.max_input_tokens = max(
            512,
            int(os.getenv("MODEL_MAX_INPUT_TOKENS", "2800")),
        )
        self.max_new_tokens = max(
            96,
            int(os.getenv("MODEL_MAX_NEW_TOKENS", "256")),
        )
        self.max_generation_seconds = max(
            15.0,
            float(os.getenv("MODEL_MAX_GENERATION_SECONDS", "90")),
        )
        self.threads = max(1, int(os.getenv("MODEL_THREADS", "2")))
        self.threads_batch = max(
            1,
            int(os.getenv("MODEL_THREADS_BATCH", str(self.threads))),
        )
        self.temperature = max(
            0.0,
            float(os.getenv("MODEL_TEMPERATURE", "0.1")),
        )
        self.top_p = min(
            1.0,
            max(0.01, float(os.getenv("MODEL_TOP_P", "0.9"))),
        )
        self.seed = int(os.getenv("MODEL_SEED", "17"))
        self.use_mmap = env_bool("MODEL_USE_MMAP", True)
        self.prompt_cache_mb = max(
            0,
            int(os.getenv("MODEL_PROMPT_CACHE_MB", "256")),
        )
        self.model = None
        self.model_path = None
        self.model_name = None
        self.load_error = None
        self.load_seconds = None
        self.last_generation = None
        self.load_lock = threading.Lock()
        self.generation_lock = threading.Lock()

    def _download_model(self):
        try:
            from huggingface_hub import hf_hub_download
        except ImportError as error:
            raise RuntimeError(
                "huggingface_hub is required for the configured Granite GGUF backend."
            ) from error

        return hf_hub_download(
            repo_id=self.model_repo,
            filename=self.model_file,
            revision=self.model_revision,
            cache_dir=self.cache_dir,
            local_files_only=self.local_files_only,
        )

    def _load_model(self):
        try:
            from llama_cpp import Llama, LlamaRAMCache
        except ImportError as error:
            raise RuntimeError(
                "llama-cpp-python is required for the configured Granite GGUF backend."
            ) from error

        model_path = self._download_model()
        model = Llama(
            model_path=model_path,
            n_ctx=self.context_tokens,
            n_batch=self.batch_tokens,
            n_threads=self.threads,
            n_threads_batch=self.threads_batch,
            n_gpu_layers=0,
            seed=self.seed,
            use_mmap=self.use_mmap,
            use_mlock=False,
            verbose=False,
        )

        if self.prompt_cache_mb > 0:
            model.set_cache(
                LlamaRAMCache(
                    capacity_bytes=self.prompt_cache_mb * 1024 * 1024
                )
            )

        return model_path, model

    def load(self):
        if not self.enabled:
            raise RuntimeError("LLM inference is disabled.")

        if self.model is not None:
            return self.model

        with self.load_lock:
            if self.model is not None:
                return self.model

            started = time.monotonic()
            try:
                model_path, model = self._load_model()
                self.model_path = model_path
                self.model = model
                self.model_name = self.primary_model
                self.load_error = None
                self.load_seconds = round(time.monotonic() - started, 3)
                return model
            except Exception as error:
                self.model = None
                self.model_path = None
                self.model_name = None
                self.load_error = repr(error)
                self.load_seconds = round(time.monotonic() - started, 3)
                gc.collect()
                raise RuntimeError(self.load_error) from error

    def _count_message_tokens(self, model, messages):
        serialized = json.dumps(
            messages,
            ensure_ascii=False,
            separators=(",", ":"),
        ).encode("utf-8")

        try:
            tokens = model.tokenize(serialized, add_bos=False, special=True)
        except TypeError:
            tokens = model.tokenize(serialized, add_bos=False)

        return len(tokens)

    def _count_text_tokens(self, model, text):
        if not text:
            return 0
        value = str(text).encode("utf-8")
        try:
            tokens = model.tokenize(value, add_bos=False, special=True)
        except TypeError:
            tokens = model.tokenize(value, add_bos=False)
        return len(tokens)

    def _json_complete(self, text):
        candidate = str(text or "").strip()
        if not candidate.startswith("{") or not candidate.endswith("}"):
            return False
        try:
            json.loads(candidate)
            return True
        except json.JSONDecodeError:
            return False

    def _extract_json_object(self, text):
        candidate = str(text or "").strip()
        if not candidate:
            return None
        if candidate.startswith("```"):
            candidate = re.sub(r"^```(?:json)?\s*", "", candidate, flags=re.IGNORECASE).strip()
            candidate = re.sub(r"\s*```$", "", candidate).strip()
        try:
            json.loads(candidate)
            return candidate
        except json.JSONDecodeError:
            pass

        start = candidate.find("{")
        if start < 0:
            return None

        depth = 0
        in_string = False
        escape = False

        for index in range(start, len(candidate)):
            char = candidate[index]
            if in_string:
                if escape:
                    escape = False
                elif char == "\\":
                    escape = True
                elif char == '"':
                    in_string = False
                continue

            if char == '"':
                in_string = True
            elif char == "{":
                depth += 1
            elif char == "}":
                depth -= 1
                if depth == 0:
                    extracted = candidate[start : index + 1].strip()
                    try:
                        json.loads(extracted)
                        return extracted
                    except json.JSONDecodeError:
                        return None
        return None

    def generate(self, messages):
        self.last_generation = None
        model = self.load()

        with self.generation_lock:
            input_tokens = self._count_message_tokens(model, messages)
            if input_tokens > self.max_input_tokens:
                raise RuntimeError(
                    f"Model input contains approximately {input_tokens} tokens, exceeding the configured limit of {self.max_input_tokens}."
                )

            started = time.monotonic()
            parts = []
            finish_reason = None
            timed_out = False
            first_content_seconds = None
            stream = model.create_chat_completion(
                messages=messages,
                response_format={
                    "type": "json_object",
                    "schema": MODEL_RESPONSE_SCHEMA,
                },
                max_tokens=self.max_new_tokens,
                temperature=self.temperature,
                top_p=self.top_p,
                seed=self.seed,
                stream=True,
            )

            try:
                for chunk in stream:
                    elapsed = time.monotonic() - started
                    choices = chunk.get("choices") or []
                    if choices:
                        choice = choices[0]
                        delta = choice.get("delta") or {}
                        content = delta.get("content")
                        if content:
                            if first_content_seconds is None:
                                first_content_seconds = elapsed
                            parts.append(str(content))
                            if self._json_complete("".join(parts)):
                                finish_reason = "json_complete"
                                break
                        if choice.get("finish_reason"):
                            finish_reason = str(choice.get("finish_reason"))

                    if elapsed >= self.max_generation_seconds and not finish_reason:
                        timed_out = True
                        break
            finally:
                close = getattr(stream, "close", None)
                if callable(close):
                    close()

            elapsed = time.monotonic() - started
            text = "".join(parts).strip()
            completion_tokens = self._count_text_tokens(model, text)
            tokens_per_second = (
                round(completion_tokens / elapsed, 3)
                if elapsed > 0 and completion_tokens
                else 0.0
            )
            self.last_generation = {
                "backend": "llama.cpp",
                "quantization": self.quantization,
                "input_tokens_approx": input_tokens,
                "completion_tokens": completion_tokens,
                "elapsed_seconds": round(elapsed, 3),
                "first_content_seconds": (
                    round(first_content_seconds, 3)
                    if first_content_seconds is not None
                    else None
                ),
                "tokens_per_second": tokens_per_second,
                "finish_reason": finish_reason,
                "timed_out": timed_out,
                "max_generation_seconds": self.max_generation_seconds,
                "max_new_tokens": self.max_new_tokens,
            }

            if timed_out:
                raise RuntimeError(
                    "The configured Granite model exceeded the generation time limit "
                    f"(generated_tokens={completion_tokens}, elapsed_seconds={elapsed:.3f}, tokens_per_second={tokens_per_second:.3f})."
                )

            if not text:
                raise RuntimeError("The configured Granite model returned an empty response.")

            json_text = self._extract_json_object(text)
            if not json_text:
                raise RuntimeError(
                    "The configured Granite JSON-constrained generation returned invalid JSON."
                )
            if json_text != text:
                self.last_generation["json_recovered"] = True
                text = json_text
            else:
                self.last_generation["json_recovered"] = False

            if finish_reason == "length":
                raise RuntimeError(
                    "The configured Granite model reached the output token limit before completing the repair plan."
                )

            return text

    def status(self):
        if not self.enabled:
            state = "disabled"
        elif self.model is not None:
            state = "loaded"
        elif self.load_error:
            state = "load_failed"
        else:
            state = "not_loaded"

        return {
            "enabled": self.enabled,
            "loaded": self.model is not None,
            "state": state,
            "backend": "llama.cpp",
            "configured_model": self.primary_model,
            "active_model": self.model_name,
            "model_repo": self.model_repo,
            "model_file": self.model_file,
            "model_revision": self.model_revision,
            "quantization": self.quantization,
            "load_error": self.load_error,
            "load_seconds": self.load_seconds,
            "context_tokens": self.context_tokens,
            "max_input_tokens": self.max_input_tokens,
            "max_new_tokens": self.max_new_tokens,
            "max_generation_seconds": self.max_generation_seconds,
            "threads": self.threads,
            "prompt_cache_mb": self.prompt_cache_mb,
            "last_generation": self.last_generation,
        }


model_service = ModelService()

app = FastAPI(
    title="Stitch QA Defect Resolution Intelligence Analyst",
    version=AGENT_VERSION,
)


def runtime_findings(request):
    analysis = request.runtime_analysis or {}
    result = []

    for index, group in enumerate(
        normalize_list(analysis.get("root_cause_groups")),
        start=1,
    ):
        if not isinstance(group, dict):
            continue

        ref = clean_text(group.get("group_id"), 80) or f"RQI-{index:03d}"
        evidence = []
        locations = []

        for item in normalize_list(group.get("evidence"))[:8]:
            if not isinstance(item, dict):
                continue
            evidence.append(
                {
                    key: item.get(key)
                    for key in (
                        "failure_id",
                        "test_name",
                        "expected",
                        "actual",
                        "exception_type",
                        "exception_message",
                        "application_file",
                        "application_line",
                        "test_file",
                        "test_line",
                    )
                    if item.get(key) not in {None, ""}
                }
            )
            file_path = item.get("application_file") or item.get("test_file")
            line = item.get("application_line") or item.get("test_line")
            if file_path:
                locations.append(
                    f"{file_path}:{line}" if line else str(file_path)
                )

        result.append(
            {
                "ref": ref,
                "source": "runtime",
                "severity": normalize_risk(
                    analysis.get("runtime_risk_level") or "HIGH"
                ),
                "title": clean_text(group.get("title"), 180)
                or "Runtime failure group",
                "category": clean_text(group.get("category"), 120),
                "root_cause": clean_text(group.get("root_cause"), 700),
                "impact": clean_text(group.get("runtime_impact"), 500),
                "recommendation": clean_text(group.get("required_action"), 500),
                "locations": list(dict.fromkeys(locations))[:8],
                "evidence": evidence,
            }
        )

    if result:
        return result

    runtime_evidence = request.runtime_evidence or {}
    test_result = str(runtime_evidence.get("test_result") or "").upper()

    for index, failure in enumerate(
        normalize_list(runtime_evidence.get("failures")),
        start=1,
    ):
        if not isinstance(failure, dict):
            continue

        ref = clean_text(failure.get("id"), 80) or f"RTE-{index:03d}"
        application_file = failure.get("application_file")
        application_line = failure.get("application_line")
        test_file = failure.get("test_file")
        test_line = failure.get("test_line")
        locations = []

        if application_file:
            locations.append(
                f"{application_file}:{application_line}"
                if application_line
                else str(application_file)
            )
        if test_file:
            locations.append(
                f"{test_file}:{test_line}"
                if test_line
                else str(test_file)
            )

        expected = clean_text(failure.get("expected"), 180)
        actual = clean_text(
            failure.get("actual") or failure.get("exception_type"),
            180,
        )
        exception_message = clean_text(failure.get("exception_message"), 300)
        observed = exception_message or actual or "The tested path failed."
        contract_text = (
            f" Expected {expected}; observed {actual}."
            if expected and actual
            else ""
        )

        result.append(
            {
                "ref": ref,
                "source": "runtime",
                "severity": "HIGH" if test_result == "FAIL" else "MEDIUM",
                "title": clean_text(
                    failure.get("test_name") or failure.get("exception_type"),
                    180,
                ) or "Validated runtime failure",
                "category": "VALIDATED_RUNTIME_FAILURE",
                "root_cause": clean_text(
                    f"Observed failure evidence: {observed}.{contract_text}",
                    700,
                ),
                "impact": (
                    "A validated automated-test path did not complete with its expected behavior."
                ),
                "recommendation": (
                    "Resolve the evidence-backed behavior mismatch using the smallest safe change, then rerun the affected and regression tests."
                ),
                "locations": list(dict.fromkeys(locations)),
                "evidence": [
                    {
                        key: failure.get(key)
                        for key in (
                            "id",
                            "test_name",
                            "expected",
                            "actual",
                            "exception_type",
                            "exception_message",
                            "application_file",
                            "application_line",
                            "test_file",
                            "test_line",
                        )
                        if failure.get(key) not in {None, ""}
                    }
                ],
            }
        )

    return result


def runtime_warning_findings(request):
    analysis = request.runtime_analysis or {}
    runtime_evidence = request.runtime_evidence or {}
    warnings = []
    seen = set()

    for item in [
        *normalize_list(analysis.get("warnings")),
        *normalize_list(runtime_evidence.get("warnings")),
    ]:
        warning = clean_text(item, 500)
        key = warning.lower()
        if not warning or key in seen:
            continue
        seen.add(key)
        warnings.append(warning)

    release_gate = str(analysis.get("release_gate") or "").upper()
    severity = "MEDIUM" if release_gate == "ALLOW_WITH_WARNINGS" else "LOW"

    return [
        {
            "ref": f"RWI-{index:03d}",
            "source": "runtime",
            "severity": severity,
            "title": "Runtime warning requiring follow-up",
            "category": "RUNTIME_WARNING",
            "root_cause": warning,
            "impact": (
                "The validated run completed, but the warning may affect future compatibility, reliability, or execution behavior if its underlying condition changes."
            ),
            "recommendation": (
                "Review the warning-specific configuration or dependency behavior, verify current vendor guidance when needed, and rerun the relevant workflow after any targeted adjustment."
            ),
            "locations": [],
            "evidence": [],
        }
        for index, warning in enumerate(warnings, start=1)
    ]


def source_findings(request):
    source_review = request.source_review or {}
    result = []

    for index, finding in enumerate(
        normalize_list(source_review.get("findings")),
        start=1,
    ):
        if not isinstance(finding, dict):
            continue

        ref = clean_text(finding.get("id"), 80) or f"SRC-{index:03d}"
        file_path = finding.get("file_path")
        line = finding.get("line")
        location = None
        if file_path:
            location = f"{file_path}:{line}" if line else str(file_path)

        result.append(
            {
                "ref": ref,
                "source": "source",
                "severity": normalize_risk(finding.get("severity")),
                "title": clean_text(finding.get("title"), 180)
                or "Source-code finding",
                "category": clean_text(finding.get("category"), 120),
                "root_cause": clean_text(
                    finding.get("evidence") or finding.get("description"),
                    700,
                ),
                "impact": clean_text(finding.get("impact"), 500),
                "recommendation": clean_text(
                    finding.get("recommendation"),
                    500,
                ),
                "locations": [location] if location else [],
                "evidence": [],
            }
        )

    return result


def execution_finding(request):
    if request.success:
        return None

    analysis = request.runtime_analysis or {}
    if normalize_list(analysis.get("root_cause_groups")):
        return None

    runtime_evidence = request.runtime_evidence or {}
    if normalize_list(runtime_evidence.get("failures")):
        return None

    failure_type = clean_text(request.failure_type, 120)
    help_message = clean_text(request.help_message, 500)
    discovery_only_failures = {
        "PYTHON_TESTS_NOT_FOUND",
    }

    if failure_type.upper() in discovery_only_failures:
        return None

    if "no test files" in help_message.lower() or "no pytest-compatible test" in help_message.lower():
        return None

    if not failure_type and not help_message:
        return None

    return {
        "ref": "EXEC-001",
        "source": "execution",
        "severity": "MEDIUM",
        "title": (
            failure_type.replace("_", " ").title()
            if failure_type
            else "Execution blocker"
        ),
        "category": "EXECUTION_BLOCKER",
        "root_cause": help_message or "Execution did not produce a validated repairable runtime result.",
        "impact": "The intended QA workflow cannot establish complete runtime assurance until this blocker is resolved.",
        "recommendation": "Resolve the execution blocker and rerun Stitch QA before making application-code repair decisions.",
        "locations": [],
        "evidence": [],
    }


def collect_locked_findings(request):
    findings = []
    findings.extend(runtime_findings(request))
    findings.extend(runtime_warning_findings(request))
    findings.extend(source_findings(request))
    execution = execution_finding(request)
    if execution:
        findings.append(execution)

    seen = set()
    normalized = []
    for finding in findings:
        ref = finding["ref"]
        if ref in seen:
            continue
        seen.add(ref)
        normalized.append(finding)

    return normalized


def select_ai_findings(findings):
    source_order = {
        "execution": 0,
        "runtime": 1,
        "source": 2,
    }

    ordered = sorted(
        findings,
        key=lambda finding: (
            -RISK_ORDER.get(normalize_risk(finding.get("severity")), -1),
            source_order.get(str(finding.get("source") or ""), 3),
            str(finding.get("ref") or ""),
        ),
    )
    return ordered[:MAX_AI_FINDINGS], ordered[MAX_AI_FINDINGS:]


def overall_priority_floor(request, findings):
    analysis = request.runtime_analysis or {}
    release_gate = str(analysis.get("release_gate") or "").upper()

    if release_gate == "BLOCK_RELEASE":
        return "P1"

    runtime_evidence = request.runtime_evidence or {}
    if str(runtime_evidence.get("test_result") or "").upper() == "FAIL":
        return "P1"

    if any(
        finding.get("source") == "execution"
        for finding in findings
    ):
        return "P1"

    if any(
        normalize_risk(finding.get("severity")) == "CRITICAL"
        for finding in findings
    ):
        return "P1"

    return "P3"


def contract_priority_floor(request, contract, findings):
    refs = set(contract.finding_refs)
    selected = [finding for finding in findings if finding.get("ref") in refs]

    if any(finding.get("source") == "execution" for finding in selected):
        return "P1"

    runtime_evidence = request.runtime_evidence or {}
    if (
        str(runtime_evidence.get("test_result") or "").upper() == "FAIL"
        and any(finding.get("source") == "runtime" for finding in selected)
    ):
        return "P1"

    return max(
        (severity_priority(finding.get("severity")) for finding in selected),
        key=lambda item: PRIORITY_ORDER[item],
        default="P3",
    )

def deterministic_confidence(request, findings):
    analysis = request.runtime_analysis or {}
    runtime_confidence = str(
        analysis.get("diagnosis_confidence") or ""
    ).upper()

    if runtime_confidence in {"HIGH", "MEDIUM", "LOW"}:
        return runtime_confidence

    source_review = request.source_review or {}
    source_confidences = {
        str(item.get("confidence") or "").upper()
        for item in normalize_list(source_review.get("findings"))
        if isinstance(item, dict)
    }

    if source_confidences == {"HIGH"}:
        return "HIGH"

    return "MEDIUM" if findings else "HIGH"


def fallback_contract(finding, index, request):
    priority = severity_priority(finding.get("severity"))

    if finding.get("source") == "execution":
        priority = "P1"

    specialized = build_specialized_contract_semantics(
        [finding],
        request,
        priority,
    )
    if specialized:
        return {
            "contract_id": f"STITCH-RC-{index:03d}",
            "finding_refs": [finding["ref"]],
            "title": clean_text(finding.get("title"), 140),
            "priority": priority,
            "priority_reason": specialized["priority_reason"],
            "repair_objective": specialized["repair_objective"],
            "repair_strategy": specialized["repair_strategy"],
            "change_boundary": specialized["change_boundary"],
            "protected_behavior": specialized["protected_behavior"],
            "side_effect_risk": specialized["side_effect_risk"],
            "verification": specialized["verification"],
            "done_condition": specialized["done_condition"],
            "status": "PENDING_VERIFICATION",
        }

    objective = (
        finding.get("recommendation")
        or f"Resolve the confirmed condition represented by {finding['ref']}."
    )
    strategy = (
        finding.get("recommendation")
        or "Apply the smallest targeted change that resolves the confirmed condition without broad unrelated changes."
    )

    runtime_analysis = request.runtime_analysis or {}
    verification_steps = normalize_list(
        runtime_analysis.get("verification_steps")
    )
    verification = (
        " ".join(clean_text(item, 180) for item in verification_steps[:3])
        if verification_steps
        else "Confirm the affected behavior first, then run the relevant regression suite and verify no new failures."
    )

    return {
        "contract_id": f"STITCH-RC-{index:03d}",
        "finding_refs": [finding["ref"]],
        "title": clean_text(finding.get("title"), 140),
        "priority": priority,
        "priority_reason": (
            f"{finding['ref']} is prioritized from its validated impact and current QA blocking effect."
        ),
        "repair_objective": clean_text(objective, 260),
        "repair_strategy": clean_text(strategy, 320),
        "change_boundary": (
            "Limit the change to the component, input boundary, dependency, or configuration directly represented by this finding."
        ),
        "protected_behavior": (
            "Preserve behavior already shown to work outside the affected scope and avoid unrelated refactoring."
        ),
        "side_effect_risk": (
            "MEDIUM"
            if normalize_risk(finding.get("severity")) in {"CRITICAL", "HIGH", "MEDIUM"}
            else "LOW"
        ),
        "verification": clean_text(verification, 300),
        "done_condition": (
            f"{finding['ref']} is no longer reproducible and the relevant regression checks complete without new failures."
        ),
        "status": "PENDING_VERIFICATION",
    }



def finding_location_pairs(finding):
    pairs = set()
    for location in finding.get("locations", []):
        match = FILE_LINE_PATTERN.search(str(location))
        if not match:
            continue
        path = match.group("path").replace("\\", "/").lstrip("./")
        try:
            line = int(match.group("line"))
        except (TypeError, ValueError):
            continue
        pairs.add((path, line))
    return pairs


def correlated_with_runtime(runtime_finding, source_finding):
    if source_finding.get("source") != "source":
        return False
    runtime_pairs = finding_location_pairs(runtime_finding)
    source_pairs = finding_location_pairs(source_finding)
    if runtime_pairs and source_pairs and runtime_pairs.intersection(source_pairs):
        return True

    runtime_text = finding_semantic_text(runtime_finding)
    source_text = finding_semantic_text(source_finding)
    shared_terms = (
        "input_validation",
        "input validation",
        "validation",
        "zero divisor",
        "division by zero",
        "valueerror",
        "boundary",
    )
    return any(term in runtime_text and term in source_text for term in shared_terms)


def correlate_fallback_findings(findings):
    runtime_findings = [
        finding
        for finding in findings
        if finding.get("source") == "runtime"
    ]
    remaining = list(findings)
    groups = []

    for runtime_finding in runtime_findings:
        if runtime_finding not in remaining:
            continue
        group = [runtime_finding]
        remaining.remove(runtime_finding)
        for finding in list(remaining):
            if correlated_with_runtime(runtime_finding, finding):
                group.append(finding)
                remaining.remove(finding)
        groups.append(group)

    for finding in remaining:
        groups.append([finding])

    return groups


def grouped_fallback_contract(findings, index, request):
    primary = next(
        (finding for finding in findings if finding.get("source") == "runtime"),
        findings[0],
    )
    if any(finding.get("source") == "execution" for finding in findings):
        priority = "P1"
    elif (
        str((request.runtime_evidence or {}).get("test_result") or "").upper() == "FAIL"
        and any(finding.get("source") == "runtime" for finding in findings)
    ):
        priority = "P1"
    elif (
        str((request.runtime_analysis or {}).get("release_gate") or "").upper() == "BLOCK_RELEASE"
        and any(finding.get("source") == "runtime" for finding in findings)
    ):
        priority = "P1"
    else:
        priority = max(
            (severity_priority(finding.get("severity")) for finding in findings),
            key=lambda item: PRIORITY_ORDER[item],
            default="P3",
        )

    specialized = build_specialized_contract_semantics(
        findings,
        request,
        priority,
    )
    if specialized:
        return {
            "contract_id": f"STITCH-RC-{index:03d}",
            "finding_refs": [finding["ref"] for finding in findings],
            "title": clean_text(primary.get("title"), 140),
            "priority": priority,
            "priority_reason": specialized["priority_reason"],
            "repair_objective": specialized["repair_objective"],
            "repair_strategy": specialized["repair_strategy"],
            "change_boundary": specialized["change_boundary"],
            "protected_behavior": specialized["protected_behavior"],
            "side_effect_risk": specialized["side_effect_risk"],
            "verification": specialized["verification"],
            "done_condition": specialized["done_condition"],
            "status": "PENDING_VERIFICATION",
        }

    objective = (
        primary.get("recommendation")
        or f"Resolve the confirmed condition represented by {', '.join(finding['ref'] for finding in findings)}."
    )
    strategy = (
        primary.get("recommendation")
        or "Apply the smallest targeted change that resolves the confirmed condition without broad unrelated changes."
    )

    runtime_analysis = request.runtime_analysis or {}
    verification_steps = normalize_list(
        runtime_analysis.get("verification_steps")
    )
    verification = (
        " ".join(clean_text(item, 180) for item in verification_steps[:3])
        if verification_steps
        else "Confirm the affected behavior first, then run the relevant regression suite and verify no new failures."
    )

    locations = []
    for finding in findings:
        for location in finding.get("locations", []):
            value = clean_text(location, 120)
            if value and value not in locations:
                locations.append(value)

    if locations:
        boundary = (
            "Limit changes to the behavior represented by "
            f"{', '.join(locations[:6])}; do not broaden the repair into unrelated files or refactoring."
        )
    else:
        boundary = (
            "Limit the change to the local input boundary or component directly represented by this evidence; do not broaden the repair into unrelated files or refactoring."
        )

    return {
        "contract_id": f"STITCH-RC-{index:03d}",
        "finding_refs": [finding["ref"] for finding in findings],
        "title": clean_text(primary.get("title"), 140),
        "priority": priority,
        "priority_reason": (
            f"{', '.join(finding['ref'] for finding in findings)} are correlated repair evidence for the same affected behavior and are prioritized from the validated QA impact."
        ),
        "repair_objective": clean_text(objective, 260),
        "repair_strategy": clean_text(strategy, 320),
        "change_boundary": clean_text(boundary, 500),
        "protected_behavior": (
            "Preserve behavior already shown to work outside the affected scope and avoid unrelated refactoring."
        ),
        "side_effect_risk": (
            "MEDIUM"
            if highest_risk(*(finding.get("severity") for finding in findings)) in {"CRITICAL", "HIGH", "MEDIUM"}
            else "LOW"
        ),
        "verification": clean_text(verification, 300),
        "done_condition": (
            f"{', '.join(finding['ref'] for finding in findings)} no longer reproduce and the relevant regression checks complete without new failures."
        ),
        "status": "PENDING_VERIFICATION",
    }

def finding_may_need_current_knowledge(finding):
    text = " ".join(
        clean_text(finding.get(key), 500).lower()
        for key in (
            "title",
            "category",
            "root_cause",
            "impact",
            "recommendation",
        )
    )
    explicit_current_signals = (
        "current trusted documentation",
        "current documentation",
        "current framework",
        "current vendor",
        "current security advisory",
        "security advisory",
        "cve",
        "deprecation",
        "deprecated",
        "vendor guidance",
        "vendor documentation",
        "release notes",
        "migration guide",
        "version compatibility",
        "dependency version",
        "package version",
        "plugin version",
        "jdk version",
        "framework release",
        "breaking change",
    )
    if any(signal in text for signal in explicit_current_signals):
        return True
    contextual_pairs = (
        ("dependency", "version"),
        ("dependency", "compatibility"),
        ("dependency", "upgrade"),
        ("dependency", "release"),
        ("framework", "version"),
        ("framework", "compatibility"),
        ("plugin", "compatibility"),
        ("jdk", "compatibility"),
        ("repository", "advisory"),
    )
    return any(first in text and second in text for first, second in contextual_pairs)


def finding_semantic_text(finding):
    return " ".join(
        clean_text(finding.get(key), 500).lower()
        for key in (
            "title",
            "category",
            "root_cause",
            "impact",
        )
    )


def is_environment_blocker_finding(finding):
    source = str(finding.get("source") or "").lower()
    category = str(finding.get("category") or "").upper()
    return source == "execution" or category == "ENVIRONMENT"


def is_missing_tests_finding(finding):
    if str(finding.get("source") or "").lower() != "source":
        return False
    text = finding_semantic_text(finding)
    indicators = (
        "no automated tests",
        "no automated test",
        "no tests detected",
        "no test files detected",
        "no test files were detected",
        "missing automated tests",
        "automated tests not detected",
    )
    return any(indicator in text for indicator in indicators)


def findings_are_environment_blockers(findings):
    return bool(findings) and all(
        is_environment_blocker_finding(finding)
        for finding in findings
    )


def findings_are_missing_tests(findings):
    return bool(findings) and all(
        is_missing_tests_finding(finding)
        for finding in findings
    )


def build_specialized_contract_semantics(findings, request, priority):
    if findings_are_environment_blockers(findings):
        recommendation = next(
            (
                clean_text(finding.get("recommendation"), 220)
                for finding in findings
                if clean_text(finding.get("recommendation"), 220)
            ),
            "Restore the required build or test execution environment.",
        )
        command = clean_text(request.command, 160) or "the validated test command"
        return {
            "priority_reason": clean_text(
                f"{priority}: runtime validation could not start because the required execution environment or build tooling was unavailable; resolve the blocker before runtime QA can be completed.",
                220,
            ),
            "repair_objective": clean_text(
                f"Restore the execution capability required to run {command} and produce runtime test evidence.",
                260,
            ),
            "repair_strategy": clean_text(
                f"Resolve only the execution-environment blocker: {recommendation} Do not modify application source code to solve an environment or build-tool availability problem.",
                320,
            ),
            "change_boundary": (
                "Limit changes to build-tool availability, environment configuration, or project wrapper files required to start the validated command; keep application source code outside this repair."
            ),
            "protected_behavior": (
                "Preserve application source and test behavior; this repair should only restore the environment needed to execute the existing test workflow."
            ),
            "side_effect_risk": "MEDIUM",
            "verification": clean_text(
                f"Confirm {command} can start, rerun Stitch QA to obtain runtime evidence, then use the resulting complete test run as regression evidence and separate any application failures from this environment blocker.",
                300,
            ),
            "done_condition": (
                "The validated test command starts successfully and Stitch QA obtains runtime evidence; any subsequent application failure is handled as a separate evidence-backed finding."
            ),
        }

    if findings_are_missing_tests(findings):
        severity = highest_risk(
            *(finding.get("severity") for finding in findings)
        )
        severity_text = (
            severity
            if severity not in {"UNKNOWN", "NONE"}
            else "confirmed"
        )
        return {
            "priority_reason": clean_text(
                f"{priority}: the {severity_text} source-review finding confirms that automated tests are absent, leaving application behavior without automated regression evidence.",
                220,
            ),
            "repair_objective": (
                "Add a focused automated test suite for the discovered application source without changing production behavior solely to satisfy the missing-tests finding."
            ),
            "repair_strategy": (
                "Add focused tests using the detected project test conventions, covering core behavior and evidence-backed edge or error paths; keep production code unchanged unless a separate validated finding requires a source repair."
            ),
            "change_boundary": (
                "Limit changes to test files and test configuration needed for discovery and execution; do not modify application behavior unless a separate validated finding requires it."
            ),
            "protected_behavior": (
                "Preserve existing application behavior while adding tests; do not introduce production-code changes solely to resolve the missing-tests finding."
            ),
            "side_effect_risk": "MEDIUM",
            "verification": (
                "Confirm the new tests are discovered, execute them, then run all existing project checks and verify the test-suite changes introduce no regression."
            ),
            "done_condition": (
                "Automated tests are discovered and execute successfully, and existing application behavior remains unchanged unless a separate validated finding requires a source repair."
            ),
        }

    return None


def build_fallback_plan(request, findings, mode="deterministic-fallback", llm_error=None):
    if not findings:
        return {
            "agent_id": AGENT_ID,
            "display_name": DISPLAY_NAME,
            "agent_version": AGENT_VERSION,
            "agent": "repair-agent",
            "mode": "evidence-validated",
            "model": None,
            "status": (
                "NO_REPAIR_REQUIRED"
                if request.success
                else "NO_CONFIRMED_REPAIR_TARGET"
            ),
            "overall_priority": "NONE",
            "confidence": "HIGH",
            "repair_risk_level": "NONE",
            "auto_apply": False,
            "summary": (
                "No confirmed repair target was supplied by runtime or source-review evidence."
                if request.success
                else "Execution did not succeed, but no evidence-grounded repair target was available; no source change should be guessed."
            ),
            "stitch_repair_contracts": [],
            "current_knowledge_required": False,
            "current_knowledge_reason": None,
            "next_action": (
                "Retain the available QA evidence and continue the normal release workflow."
                if request.success
                else "Obtain a confirmed runtime, execution, or source-review finding before planning a code repair."
            ),
            "suggestions": [],
            "warnings": [],
            "limitations": [
                "Agent 2 only plans repairs for findings supplied by validated Stitch QA evidence."
            ],
            "llm_metrics": model_service.last_generation,
            "llm_error": llm_error,
        }

    grouped_findings = correlate_fallback_findings(findings)
    contracts = [
        grouped_fallback_contract(group, index, request)
        for index, group in enumerate(grouped_findings, start=1)
    ]
    contracts = sort_and_renumber_contracts(contracts)
    highest_priority = max(
        (contract["priority"] for contract in contracts),
        key=lambda item: PRIORITY_ORDER[item],
        default="P3",
    )
    floor = overall_priority_floor(request, findings)
    if PRIORITY_ORDER[highest_priority] < PRIORITY_ORDER[floor]:
        highest_priority = floor

    repair_risk = highest_risk(
        *(contract["side_effect_risk"] for contract in contracts)
    )

    warnings = []

    return {
        "agent_id": AGENT_ID,
        "display_name": DISPLAY_NAME,
        "agent_version": AGENT_VERSION,
        "agent": "repair-agent",
        "mode": mode,
        "model": model_service.model_name or model_service.primary_model,
        "status": "COMPLETED",
        "overall_priority": highest_priority,
        "confidence": deterministic_confidence(request, findings),
        "repair_risk_level": repair_risk,
        "auto_apply": False,
        "summary": (
            f"Prepared {len(contracts)} evidence-linked repair contract"
            f"{'s' if len(contracts) != 1 else ''} from {len(findings)} confirmed finding"
            f"{'s' if len(findings) != 1 else ''}."
        ),
        "stitch_repair_contracts": contracts,
        "current_knowledge_required": any(
            finding_may_need_current_knowledge(finding)
            for finding in findings
        ),
        "current_knowledge_reason": (
            "One or more repair targets depend on version, dependency, compatibility, vendor, deprecation, or security information that should be verified against current trusted documentation."
            if any(
                finding_may_need_current_knowledge(finding)
                for finding in findings
            )
            else None
        ),
        "next_action": (
            f"Start with {contracts[0]['contract_id']} and verify its done condition before broadening the repair scope."
        ),
        "suggestions": [
            contract["repair_strategy"]
            for contract in contracts
        ],
        "warnings": warnings,
        "limitations": [
            "This repair plan is grounded in supplied Stitch QA findings and does not automatically modify project code.",
            "Deterministic fallback prioritization is conservative and may be less context-sensitive than validated AI planning.",
        ],
        "llm_metrics": model_service.last_generation,
        "llm_error": llm_error,
    }


def compact_model_evidence(items):
    compacted = []
    for item in normalize_list(items)[:2]:
        if not isinstance(item, dict):
            continue
        compacted.append(
            {
                "id": clean_text(item.get("failure_id") or item.get("id"), 60),
                "test": clean_text(item.get("test_name"), 160),
                "expected": clean_text(item.get("expected"), 120),
                "actual": clean_text(item.get("actual"), 120),
                "exception": clean_text(item.get("exception_type"), 100),
                "message": clean_text(item.get("exception_message"), 220),
                "application": clean_text(item.get("application_file"), 200),
                "application_line": item.get("application_line"),
                "test_file": clean_text(item.get("test_file"), 200),
                "test_line": item.get("test_line"),
            }
        )
    return [
        {key: value for key, value in item.items() if value not in {None, ""}}
        for item in compacted
    ]


def model_input_findings(findings):
    payload = []

    for finding in findings[:MAX_AI_FINDINGS]:
        payload.append(
            {
                "ref": finding["ref"],
                "source": finding["source"],
                "severity": finding["severity"],
                "title": clean_text(finding.get("title"), 100),
                "category": clean_text(finding.get("category"), 70),
                "cause": clean_text(finding.get("root_cause"), 240),
                "impact": clean_text(finding.get("impact"), 180),
                "existing_action": clean_text(finding.get("recommendation"), 180),
                "locations": [
                    clean_text(location, 160)
                    for location in finding.get("locations", [])[:4]
                ],
                "evidence": compact_model_evidence(finding.get("evidence", [])),
            }
        )

    return payload


def build_messages(request, findings):
    analysis = request.runtime_analysis or {}
    source_review = request.source_review or {}

    system_prompt = (
        "You are Stitch QA's Defect Resolution Intelligence Analyst. "
        "Your job is to transform locked QA findings into the safest prioritized repair plan without editing code. "
        "The supplied finding references, severities, files, lines, test facts, release gate, and observed evidence are authoritative. "
        "Never invent findings, files, lines, test outcomes, dependency versions, vulnerabilities, or current external facts. "
        "Prioritize by impact, blocking effect, dependency order, repair scope, and regression risk; severity and repair priority are related but not identical. "
        "Group findings only when one repair objective genuinely resolves them together. "
        "For every repair contract define the smallest useful change boundary, behavior that must remain working, side-effect risk, confirmation verification, regression verification, and a measurable done condition. "
        "Repair strategy must describe the repair action and must never be only a file or line location. "
        "Change boundary must describe the permitted scope, not merely repeat locations. "
        "Protected behavior must name working behavior that should remain unchanged and must never be None, N/A, or an impact statement. "
        "Verification must include both targeted confirmation of the referenced finding and broader regression verification. "
        "Side-effect risk means risk introduced by implementing the repair, not the severity of the original defect; narrow local validation changes are normally LOW or MEDIUM unless the evidence shows broader coupling. "
        "For environment or build-tool blockers, do not call the underlying application defect critical unless the locked evidence says CRITICAL, and keep application source code outside the repair boundary unless separate source evidence requires a change. "
        "For missing-tests findings, keep the repair boundary to test files and test configuration needed for discovery and execution; do not propose production-code changes solely to create tests. "
        "Do not generate patches, code, commits, commands that modify the project, or automatic fixes. "
        "If a version, vendor behavior, dependency compatibility, deprecation, or security advisory needs up-to-date external documentation, set current_knowledge_required=true and explain why; do not invent the missing current fact. "
        "Return only JSON matching the required schema. "
        "Compact keys are fixed: p=overall priority, c=confidence, k=current-knowledge-needed, kr=current-knowledge reason, x=repair contracts; "
        "inside each contract f=finding refs, p=priority, w=priority reason, o=repair objective, s=repair strategy, b=change boundary, q=protected behavior, r=side-effect risk (L/M/H), v=verification. "
        "Keep every text value concise because the final professional report is formatted by Stitch QA."
    )

    payload = {
        "project": {
            "type": request.project_type,
            "command": request.command,
            "success": request.success,
            "exit_code": request.exit_code,
            "failure_type": request.failure_type,
        },
        "runtime_gate": {
            "test_result": analysis.get("test_result"),
            "release_gate": analysis.get("release_gate"),
            "runtime_risk": analysis.get("runtime_risk_level"),
            "confidence": analysis.get("diagnosis_confidence"),
            "evidence_quality": analysis.get("evidence_quality"),
        },
        "source_review": {
            "status": source_review.get("status"),
            "risk_level": source_review.get("risk_level"),
            "findings_count": len(
                normalize_list(source_review.get("findings"))
            ),
        },
        "locked_findings": model_input_findings(findings),
        "instructions": {
            "all_findings_must_be_covered": True,
            "contract_order_is_repair_order": True,
            "auto_apply": False,
        },
    }

    return [
        {
            "role": "system",
            "content": system_prompt,
        },
        {
            "role": "user",
            "content": json.dumps(
                payload,
                ensure_ascii=False,
                separators=(",", ":"),
            ),
        },
    ]


FILE_LINE_PATTERN = re.compile(
    r"(?P<path>[A-Za-z0-9_./\\-]+\.[A-Za-z0-9]+):(?P<line>\d+)"
)

AUTO_APPLY_PATTERNS = {
    "i modified",
    "i changed",
    "i updated",
    "automatically modified",
    "automatically fixed",
    "auto-fix applied",
    "committed the",
    "pushed the",
}


def parse_model_output(text):
    try:
        data = json.loads(str(text or "").strip())
    except json.JSONDecodeError as error:
        raise ValueError("The Granite response was not valid JSON.") from error

    try:
        return ModelRepairPlan.model_validate(data)
    except ValidationError as error:
        raise ValueError(
            f"The Granite response failed the repair-plan schema: {error}"
        ) from error


def allowed_references(findings):
    allowed = set()

    for finding in findings:
        for location in finding.get("locations", []):
            match = FILE_LINE_PATTERN.search(str(location))
            if not match:
                continue
            path = match.group("path").replace("\\", "/")
            line = int(match.group("line"))
            allowed.add((path, line))
            allowed.add((path.lstrip("./"), line))

    return allowed


def text_fields(plan):
    values = [plan.current_knowledge_reason]
    for contract in plan.contracts:
        values.extend(
            [
                contract.priority_reason,
                contract.repair_objective,
                contract.repair_strategy,
                contract.change_boundary,
                contract.protected_behavior,
                contract.verification,
            ]
        )
    return values


PLACEHOLDER_VALUES = {
    "none",
    "n/a",
    "na",
    "not applicable",
    "not available",
    "unknown",
    "null",
}

REPAIR_ACTION_TERMS = (
    "add ",
    "validate",
    "guard",
    "handle",
    "replace",
    "update",
    "configure",
    "remove",
    "restore",
    "return",
    "raise",
    "prevent",
    "resolve",
    "correct",
    "limit",
)

PROTECTION_TERMS = (
    "preserve",
    "keep",
    "maintain",
    "unchanged",
    "working",
    "valid",
    "passing",
)

REGRESSION_TERMS = (
    "regression",
    "full test",
    "complete test",
    "entire test",
    "no new failure",
    "all tests",
)

CONFIRMATION_TERMS = (
    "rerun",
    "re-run",
    "confirm",
    "verify",
    "expected",
    "affected test",
    "failing test",
)

BROAD_REPAIR_INDICATORS = (
    "dependency",
    "plugin",
    "configuration",
    "architecture",
    "migration",
    "security",
    "database",
    "schema",
    "api contract",
    "public api",
    "cross-service",
    "multiple modules",
)


def is_placeholder_text(value):
    normalized = clean_text(value, 400).lower().strip(" .:-")
    if not normalized:
        return True
    if normalized in PLACEHOLDER_VALUES:
        return True
    return any(
        normalized.startswith(f"{item}:")
        for item in PLACEHOLDER_VALUES
    )


def strip_file_line_references(value):
    text = FILE_LINE_PATTERN.sub(" ", clean_text(value, 600))
    text = re.sub(r"[\s,;:/|()\[\]{}-]+", " ", text)
    return text.strip()


def is_location_only_text(value):
    original = clean_text(value, 600)
    if not original:
        return True
    if not FILE_LINE_PATTERN.search(original):
        return False
    remainder = strip_file_line_references(original)
    return len(remainder.split()) <= 3


def selected_findings_for_contract(contract, findings):
    refs = set(contract.finding_refs)
    return [
        finding
        for finding in findings
        if finding.get("ref") in refs
    ]


def selected_locations(findings):
    locations = []
    for finding in findings:
        for location in finding.get("locations", []):
            value = clean_text(location, 180)
            if value and value not in locations:
                locations.append(value)
    return locations


def selected_test_evidence(findings):
    evidence = []
    seen = set()
    for finding in findings:
        for item in normalize_list(finding.get("evidence")):
            if not isinstance(item, dict):
                continue
            test_name = clean_text(item.get("test_name"), 180)
            expected = clean_text(item.get("expected"), 120)
            actual = clean_text(
                item.get("actual") or item.get("exception_type"),
                120,
            )
            key = (test_name, expected, actual)
            if key in seen:
                continue
            seen.add(key)
            evidence.append(
                {
                    "test_name": test_name,
                    "expected": expected,
                    "actual": actual,
                }
            )
    return evidence


def build_grounded_repair_objective(selected):
    evidence = selected_test_evidence(selected)
    expected_values = list(
        dict.fromkeys(
            item["expected"]
            for item in evidence
            if item.get("expected")
        )
    )

    if expected_values:
        return clean_text(
            f"Restore the expected {', '.join(expected_values[:3])} behavior for the referenced failing paths while preserving valid behavior outside them.",
            260,
        )

    recommendations = [
        clean_text(finding.get("recommendation"), 220)
        for finding in selected
        if clean_text(finding.get("recommendation"), 220)
    ]
    if recommendations:
        return clean_text(recommendations[0], 260)

    return (
        "Resolve the referenced evidence-backed condition without changing unrelated behavior."
    )


def build_grounded_repair_strategy(selected):
    evidence = selected_test_evidence(selected)
    locations = selected_locations(selected)
    expected_values = list(
        dict.fromkeys(
            item["expected"]
            for item in evidence
            if item.get("expected")
        )
    )
    actual_values = list(
        dict.fromkeys(
            item["actual"]
            for item in evidence
            if item.get("actual")
        )
    )

    if evidence and expected_values:
        expected_text = ", ".join(expected_values[:3])
        actual_text = ", ".join(actual_values[:3]) or "the observed failure"
        location_text = (
            f" at {', '.join(locations[:4])}"
            if locations
            else " in the affected runtime path"
        )
        return clean_text(
            f"Add targeted validation or controlled error handling{location_text} so the affected paths produce the expected {expected_text} behavior instead of {actual_text}; avoid unrelated implementation changes.",
            320,
        )

    recommendations = [
        clean_text(finding.get("recommendation"), 220)
        for finding in selected
        if clean_text(finding.get("recommendation"), 220)
    ]
    if recommendations:
        return clean_text(
            f"Apply the smallest targeted change needed to satisfy this evidence: {recommendations[0]}",
            320,
        )

    return (
        "Apply the smallest targeted change that resolves the referenced finding while avoiding unrelated refactoring or behavior changes."
    )


def build_grounded_change_boundary(selected):
    locations = selected_locations(selected)
    if locations:
        return clean_text(
            f"Limit changes to the behavior represented by {', '.join(locations[:4])}; do not broaden the repair into unrelated files or refactoring.",
            240,
        )
    return (
        "Limit changes to the component, configuration, or input boundary directly represented by the referenced finding; avoid unrelated changes."
    )


def build_grounded_protected_behavior(selected, request):
    runtime_evidence = request.runtime_evidence or {}
    test_summary = runtime_evidence.get("test_summary") or {}
    passed = int(test_summary.get("passed") or 0)

    if passed > 0:
        return clean_text(
            f"Preserve the {passed} currently passing tests and all valid-input behavior outside the referenced failure paths.",
            240,
        )

    if any(finding.get("source") == "runtime" for finding in selected):
        return (
            "Preserve currently successful runtime behavior outside the referenced failure paths and keep valid inputs unchanged."
        )

    return (
        "Preserve behavior outside the referenced source finding and avoid unrelated functional or structural changes."
    )


def build_grounded_verification(selected, request):
    evidence = selected_test_evidence(selected)
    test_names = list(
        dict.fromkeys(
            item["test_name"]
            for item in evidence
            if item.get("test_name")
        )
    )
    expected_values = list(
        dict.fromkeys(
            item["expected"]
            for item in evidence
            if item.get("expected")
        )
    )

    if test_names:
        targeted = ", ".join(test_names[:4])
        expected_text = (
            f" and confirm the expected {', '.join(expected_values[:3])} behavior"
            if expected_values
            else " and confirm the referenced failures no longer reproduce"
        )
        return clean_text(
            f"Rerun {targeted}{expected_text}; then run the complete test suite and confirm exit code 0 with no new failures.",
            300,
        )

    runtime_analysis = request.runtime_analysis or {}
    verification_steps = [
        clean_text(item, 160)
        for item in normalize_list(runtime_analysis.get("verification_steps"))
        if clean_text(item, 160)
    ]
    if verification_steps:
        base = " ".join(verification_steps[:3])
        if not any(term in base.lower() for term in REGRESSION_TERMS):
            base += " Then run the relevant regression suite and confirm no new failures."
        return clean_text(base, 300)

    return (
        "Confirm the referenced finding is resolved with a targeted check, then run all available regression tests or project checks and verify no new failure is introduced."
    )


def is_narrow_repair(selected, boundary):
    categories = " ".join(
        clean_text(finding.get("category"), 100).lower()
        for finding in selected
    )
    combined = f"{categories} {clean_text(boundary, 240).lower()}"
    if any(indicator in combined for indicator in BROAD_REPAIR_INDICATORS):
        return False

    files = set()
    for location in selected_locations(selected):
        match = FILE_LINE_PATTERN.search(location)
        if match:
            files.add(match.group("path").replace("\\", "/"))

    return len(files) <= 1


def normalize_contract_semantics(contract, request, findings):
    selected = selected_findings_for_contract(contract, findings)
    specialized = build_specialized_contract_semantics(
        selected,
        request,
        contract.priority,
    )
    if specialized:
        return specialized

    priority_reason = clean_text(contract.priority_reason, 220)
    objective = clean_text(contract.repair_objective, 260)
    expected_values = [
        item["expected"]
        for item in selected_test_evidence(selected)
        if item.get("expected")
    ]
    if (
        is_placeholder_text(objective)
        or (
            expected_values
            and not any(
                expected.lower() in objective.lower()
                for expected in expected_values
            )
        )
    ):
        objective = build_grounded_repair_objective(selected)

    strategy = clean_text(contract.repair_strategy, 320)
    if (
        is_placeholder_text(strategy)
        or is_location_only_text(strategy)
        or not any(term in strategy.lower() for term in REPAIR_ACTION_TERMS)
    ):
        strategy = build_grounded_repair_strategy(selected)

    boundary = clean_text(contract.change_boundary, 240)
    if is_placeholder_text(boundary) or is_location_only_text(boundary):
        boundary = build_grounded_change_boundary(selected)

    protected = clean_text(contract.protected_behavior, 240)
    if (
        is_placeholder_text(protected)
        or not any(term in protected.lower() for term in PROTECTION_TERMS)
    ):
        protected = build_grounded_protected_behavior(selected, request)

    verification = clean_text(contract.verification, 300)
    lowered_verification = verification.lower()
    has_confirmation = any(
        term in lowered_verification
        for term in CONFIRMATION_TERMS
    )
    has_regression = any(
        term in lowered_verification
        for term in REGRESSION_TERMS
    )
    if (
        is_placeholder_text(verification)
        or not has_confirmation
        or not has_regression
    ):
        verification = build_grounded_verification(selected, request)

    repair_risk = contract.side_effect_risk
    if repair_risk == "HIGH" and is_narrow_repair(selected, boundary):
        repair_risk = "MEDIUM"

    return {
        "priority_reason": priority_reason,
        "repair_objective": objective,
        "repair_strategy": strategy,
        "change_boundary": boundary,
        "protected_behavior": protected,
        "side_effect_risk": repair_risk,
        "verification": verification,
        "done_condition": (
            "The referenced findings no longer reproduce, the targeted confirmation succeeds, and the stated regression verification introduces no new failure."
        ),
    }

def validate_plan(plan, request, findings):
    finding_refs = {finding["ref"] for finding in findings}
    used_refs = []
    combined_text = " ".join(text_fields(plan)).lower()

    for pattern in AUTO_APPLY_PATTERNS:
        if pattern in combined_text:
            raise ValueError(
                "The Granite repair plan claimed or proposed automatic project modification."
            )

    for contract in plan.contracts:
        for ref in contract.finding_refs:
            if ref not in finding_refs:
                raise ValueError(
                    f"The Granite repair plan referenced unknown finding {ref}."
                )
            used_refs.append(ref)

    missing_refs = finding_refs - set(used_refs)
    if missing_refs:
        raise ValueError(
            "The Granite repair plan omitted confirmed findings: "
            + ", ".join(sorted(missing_refs))
        )

    duplicates = {
        ref
        for ref in used_refs
        if used_refs.count(ref) > 1
    }
    if duplicates:
        raise ValueError(
            "The Granite repair plan assigned findings to multiple repair contracts: "
            + ", ".join(sorted(duplicates))
        )

    for contract in plan.contracts:
        floor = contract_priority_floor(request, contract, findings)
        if PRIORITY_ORDER[contract.priority] < PRIORITY_ORDER[floor]:
            contract.priority = floor

    allowed = allowed_references(findings)
    for value in text_fields(plan):
        for match in FILE_LINE_PATTERN.finditer(value or ""):
            path = match.group("path").replace("\\", "/")
            line = int(match.group("line"))
            if (path, line) not in allowed and (path.lstrip("./"), line) not in allowed:
                raise ValueError(
                    "The Granite repair plan introduced an unsupported file or line reference."
                )

    floor = overall_priority_floor(request, findings)
    if PRIORITY_ORDER[plan.overall_priority] < PRIORITY_ORDER[floor]:
        plan.overall_priority = floor

    highest_contract_priority = max(
        (contract.priority for contract in plan.contracts),
        key=lambda item: PRIORITY_ORDER[item],
    )
    if PRIORITY_ORDER[plan.overall_priority] < PRIORITY_ORDER[highest_contract_priority]:
        plan.overall_priority = highest_contract_priority

    grounded_current_knowledge = any(
        finding_may_need_current_knowledge(finding)
        for finding in findings
    )
    plan.current_knowledge_required = grounded_current_knowledge
    if not grounded_current_knowledge:
        plan.current_knowledge_reason = ""

    return plan


def sort_and_renumber_contracts(contracts):
    ordered = sorted(
        contracts,
        key=lambda contract: -PRIORITY_ORDER.get(contract.get("priority", "P3"), 1),
    )
    for index, contract in enumerate(ordered, start=1):
        contract["contract_id"] = f"STITCH-RC-{index:03d}"
    return ordered


def merge_model_plan(plan, request, findings, overflow_findings=None):
    overflow_findings = list(overflow_findings or [])
    contracts = []

    for index, item in enumerate(plan.contracts, start=1):
        semantic = normalize_contract_semantics(
            item,
            request,
            findings,
        )
        contracts.append(
            {
                "contract_id": f"STITCH-RC-{index:03d}",
                "finding_refs": item.finding_refs,
                "title": clean_text(
                    f"Repair contract for {', '.join(item.finding_refs)}",
                    140,
                ),
                "priority": item.priority,
                "priority_reason": semantic["priority_reason"],
                "repair_objective": semantic["repair_objective"],
                "repair_strategy": semantic["repair_strategy"],
                "change_boundary": semantic["change_boundary"],
                "protected_behavior": semantic["protected_behavior"],
                "side_effect_risk": semantic["side_effect_risk"],
                "verification": semantic["verification"],
                "done_condition": semantic["done_condition"],
                "status": "PENDING_VERIFICATION",
            }
        )

    next_index = len(contracts) + 1
    for offset, finding in enumerate(overflow_findings):
        contract = fallback_contract(finding, next_index + offset, request)
        contracts.append(contract)

    contracts = sort_and_renumber_contracts(contracts)

    repair_risk = highest_risk(
        *(contract["side_effect_risk"] for contract in contracts)
    )

    overall_priority = plan.overall_priority
    if overflow_findings:
        overflow_priority = max(
            (severity_priority(item.get("severity")) for item in overflow_findings),
            key=lambda item: PRIORITY_ORDER[item],
            default="P3",
        )
        if PRIORITY_ORDER[overall_priority] < PRIORITY_ORDER[overflow_priority]:
            overall_priority = overflow_priority

    limitations = [
        "Agent 2 plans repairs from supplied Stitch QA evidence and does not automatically modify source code.",
        "Current external facts are not fetched inside this agent; cases marked current_knowledge_required need trusted documentation before implementation.",
    ]
    warnings = []

    if overflow_findings:
        warnings.append(
            f"{len(overflow_findings)} lower-priority finding(s) exceeded the AI reasoning window and were retained as conservative evidence-grounded repair contracts rather than being dropped."
        )
        limitations.append(
            "Overflow repair contracts use conservative deterministic planning because the AI reasoning window is intentionally bounded for CPU reliability."
        )

    summary_strategy = (
        clean_text(contracts[0]["repair_strategy"], 300).rstrip(" .")
        if contracts
        else "the highest-priority validated repair target"
    )

    return {
        "agent_id": AGENT_ID,
        "display_name": DISPLAY_NAME,
        "agent_version": AGENT_VERSION,
        "agent": "repair-agent",
        "mode": "ai-reasoned-validated",
        "model": model_service.model_name or model_service.primary_model,
        "status": "COMPLETED",
        "overall_priority": overall_priority,
        "confidence": plan.confidence,
        "repair_risk_level": repair_risk,
        "auto_apply": False,
        "summary": clean_text(
            f"Prepared {len(contracts)} prioritized evidence-linked repair contract"
            f"{'s' if len(contracts) != 1 else ''}; start with {summary_strategy}.",
            360,
        ),
        "stitch_repair_contracts": contracts,
        "current_knowledge_required": (
            plan.current_knowledge_required
            or any(
                finding_may_need_current_knowledge(finding)
                for finding in [*findings, *overflow_findings]
            )
        ),
        "current_knowledge_reason": (
            clean_text(plan.current_knowledge_reason, 240)
            if plan.current_knowledge_required and clean_text(plan.current_knowledge_reason, 240)
            else (
                "One or more repair targets depend on current version, dependency, compatibility, vendor, deprecation, or security documentation that must be verified before implementation."
                if any(
                    finding_may_need_current_knowledge(finding)
                    for finding in [*findings, *overflow_findings]
                )
                else None
            )
        ),
        "next_action": (
            f"Start with {contracts[0]['contract_id']}: {contracts[0]['repair_strategy']}"
            if contracts
            else None
        ),
        "suggestions": [
            contract["repair_strategy"]
            for contract in contracts
        ],
        "warnings": warnings,
        "limitations": limitations,
        "llm_metrics": model_service.last_generation,
        "llm_error": None,
    }

def should_use_llm(findings):
    return (
        model_service.enabled
        and bool(findings)
        and any(
            finding.get("source") in {"runtime", "source"}
            for finding in findings
        )
    )


@app.get("/")
def health_check():
    status = model_service.status()
    return {
        "service": "stitch-qa-repair-agent",
        "agent_id": AGENT_ID,
        "display_name": DISPLAY_NAME,
        "agent_version": AGENT_VERSION,
        "status": "running",
        "llm": status,
    }


@app.get("/ready")
def readiness_check():
    status = model_service.status()
    return {
        "ready": True,
        "analysis_ready": True,
        "agent_id": AGENT_ID,
        "llm_enabled": status["enabled"],
        "llm_loaded": status["loaded"],
        "llm_state": status["state"],
        "configured_model": status["configured_model"],
        "active_model": status["active_model"],
        "deterministic_fallback": True,
    }


@app.post("/suggest", response_model=RepairResponse)
def suggest_repair(request: RepairRequest):
    findings = collect_locked_findings(request)

    if not findings:
        return RepairResponse.model_validate(
            build_fallback_plan(request, findings)
        )

    if not should_use_llm(findings):
        return RepairResponse.model_validate(
            build_fallback_plan(
                request,
                findings,
                mode="deterministic-validated",
            )
        )

    ai_findings, overflow_findings = select_ai_findings(findings)

    try:
        messages = build_messages(request, ai_findings)
        text = model_service.generate(messages)
        plan = parse_model_output(text)
        plan = validate_plan(plan, request, ai_findings)
        result = merge_model_plan(
            plan,
            request,
            ai_findings,
            overflow_findings,
        )
    except Exception as error:
        result = build_fallback_plan(
            request,
            findings,
            mode="deterministic-fallback",
            llm_error=repr(error),
        )

    return RepairResponse.model_validate(result)