m1nd-mcp 0.8.0

MCP Server for m1nd. Stop letting AI grep your codebase. Neuro-symbolic connectome for AI agents.
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
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
// === m1nd-mcp/src/protocol/layers.rs ===
//
// Input/Output types for new MCP tools across Layers 1-7.
// From research reports L1-L7 and SYNTHESIS-7-LAYERS.
//
// Conventions (matching core.rs / perspective.rs / lock.rs):
//   - Input:  #[derive(Clone, Debug, Deserialize)]
//   - Output: #[derive(Clone, Debug, Serialize)]
//   - All inputs require `agent_id: String`
//   - Optional params with defaults use #[serde(default = "fn_name")]
//   - Optional Vec fields use #[serde(default)]
//   - Optional String fields use Option<String>
//   - Doc comments reference PRD layer + section

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

// =========================================================================
// L1: Cross-File Edges — New Edge Types (no new MCP tools, ingest-only)
// =========================================================================

/// New edge relation types for cross-file edges (L1-CROSS-FILE-EDGES §9).
/// Added to the relation field of ExtractedEdge during ingest.
/// Not MCP protocol types — included here for completeness.
///
/// Values used in CSR `relations` field via StringInterner:
///   "imports"     — file A imports module from file B
///   "calls"       — function in A calls function in B
///   "registers"   — A registers B as a route/plugin (e.g. include_router)
///   "configures"  — A reads config key defined/set in B
///   "tests"       — test file A tests module B
///   "inherits"    — class in A inherits from class in B
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CrossFileEdgeType {
    Imports,
    Calls,
    Registers,
    Configures,
    Tests,
    Inherits,
}

// =========================================================================
// L2: Semantic Search — m1nd.seek + m1nd.scan
// =========================================================================

// ---------------------------------------------------------------------------
// m1nd.seek (L2-SEMANTIC-SEARCH §6.1)
// ---------------------------------------------------------------------------

/// Input for m1nd.seek — intent-aware code search.
/// Finds code by PURPOSE, not text pattern.
/// Example: seek("code that validates user credentials") returns auth modules.
#[derive(Clone, Debug, Deserialize)]
pub struct SeekInput {
    /// Natural language description of what the agent is looking for.
    pub query: String,
    pub agent_id: String,
    /// Maximum results to return. Default: 20.
    #[serde(default = "default_top_k")]
    pub top_k: usize,
    /// File path prefix to limit search scope. None = entire graph.
    #[serde(default)]
    pub scope: Option<String>,
    /// Filter by node type: "function", "class", "struct", "module", "file".
    #[serde(default)]
    pub node_types: Vec<String>,
    /// Minimum combined score threshold. Default: 0.1.
    #[serde(default = "default_min_score")]
    pub min_score: f32,
    /// Whether to run graph re-ranking on embedding candidates. Default: true.
    #[serde(default = "default_true")]
    pub graph_rerank: bool,
}

/// Output for m1nd.seek.
#[derive(Clone, Debug, Serialize)]
pub struct SeekOutput {
    pub query: String,
    pub results: Vec<SeekResultEntry>,
    pub total_candidates_scanned: usize,
    /// Whether embeddings were used (false = fallback to trigram/semantic engine).
    pub embeddings_used: bool,
    /// Coarse proof stage for semantic retrieval:
    /// "blocked" | "triaging" | "proving" | "ready_to_edit".
    pub proof_state: String,
    pub elapsed_ms: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_tool: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_target: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_step_hint: Option<String>,
}

/// Shared heuristic metadata exposed by tools that apply trust/tremor priors.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HeuristicSignals {
    pub heuristic_factor: f32,
    pub trust_score: f32,
    pub trust_risk_multiplier: f32,
    pub trust_tier: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tremor_magnitude: Option<f32>,
    pub tremor_observation_count: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tremor_risk_level: Option<String>,
    pub reason: String,
}

/// A single seek result entry.
#[derive(Clone, Debug, Serialize)]
pub struct SeekResultEntry {
    pub node_id: String,
    pub label: String,
    #[serde(rename = "type")]
    pub node_type: String,
    /// Combined score: embedding * 0.5 + graph * 0.3 + temporal * 0.2.
    pub score: f32,
    pub score_breakdown: SeekScoreBreakdown,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub heuristic_signals: Option<HeuristicSignals>,
    /// Heuristic intent summary generated during ingest.
    pub intent_summary: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line_start: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line_end: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub excerpt: Option<String>,
    /// Connected nodes (callers, callees, importers).
    pub connections: Vec<SeekConnection>,
}

#[derive(Clone, Debug, Serialize)]
pub struct SeekScoreBreakdown {
    pub embedding_similarity: f32,
    pub graph_activation: f32,
    pub temporal_recency: f32,
}

#[derive(Clone, Debug, Serialize)]
pub struct SeekConnection {
    pub node_id: String,
    pub label: String,
    pub relation: String,
}

// ---------------------------------------------------------------------------
// m1nd.scan (L2-SEMANTIC-SEARCH §6.2)
// ---------------------------------------------------------------------------

/// Input for m1nd.scan — pattern-aware code analysis.
/// Detects structural issues using predefined patterns with graph-aware
/// validation across file boundaries.
#[derive(Clone, Debug, Deserialize)]
pub struct ScanInput {
    /// Pattern ID ("error_handling", "resource_cleanup", "api_surface",
    /// "state_mutation", "concurrency", "auth_boundary", "test_coverage",
    /// "dependency_injection") or a custom ast-grep pattern string.
    pub pattern: String,
    pub agent_id: String,
    /// File path prefix to limit scan scope. None = entire graph.
    #[serde(default)]
    pub scope: Option<String>,
    /// Minimum severity threshold [0.0, 1.0]. Default: 0.3.
    #[serde(default = "default_severity_min")]
    pub severity_min: f32,
    /// Whether to validate findings against graph edges (cross-file). Default: true.
    #[serde(default = "default_true")]
    pub graph_validate: bool,
    /// Maximum findings to return. Default: 50.
    #[serde(default = "default_scan_limit")]
    pub limit: usize,
}

/// Output for m1nd.scan.
#[derive(Clone, Debug, Serialize)]
pub struct ScanOutput {
    pub pattern: String,
    pub findings: Vec<ScanFinding>,
    pub files_scanned: usize,
    pub total_matches_raw: usize,
    /// Matches after graph-aware validation.
    pub total_matches_validated: usize,
    pub elapsed_ms: f64,
}

/// A single scan finding.
#[derive(Clone, Debug, Serialize)]
pub struct ScanFinding {
    pub pattern: String,
    /// "confirmed" | "mitigated" | "false_positive"
    pub status: String,
    pub severity: f32,
    pub node_id: String,
    pub label: String,
    pub file_path: String,
    pub line: u32,
    pub message: String,
    /// Related graph nodes that informed the validation decision.
    pub graph_context: Vec<ScanContextNode>,
}

#[derive(Clone, Debug, Serialize)]
pub struct ScanContextNode {
    pub node_id: String,
    pub label: String,
    pub relation: String,
}

// =========================================================================
// L3: Temporal Intelligence — m1nd.timeline + m1nd.diverge
// =========================================================================

// ---------------------------------------------------------------------------
// m1nd.timeline (L3-TEMPORAL-INTELLIGENCE §5)
// ---------------------------------------------------------------------------

/// Input for m1nd.timeline — git-based temporal history for a node.
/// Returns change history, co-change partners, velocity, and stability.
#[derive(Clone, Debug, Deserialize)]
pub struct TimelineInput {
    /// Node external_id (e.g. "file::backend/chat_handler.py").
    pub node: String,
    pub agent_id: String,
    /// Time depth: "7d", "30d", "90d", "all". Default: "30d".
    #[serde(default = "default_depth_30d")]
    pub depth: String,
    /// Include co-changed files with coupling scores. Default: true.
    #[serde(default = "default_true")]
    pub include_co_changes: bool,
    /// Include lines added/deleted churn data. Default: true.
    #[serde(default = "default_true")]
    pub include_churn: bool,
    /// Max co-change partners to return. Default: 10.
    #[serde(default = "default_top_k_10")]
    pub top_k: usize,
}

/// Output for m1nd.timeline.
#[derive(Clone, Debug, Serialize)]
pub struct TimelineOutput {
    pub node: String,
    pub depth: String,
    /// Coarse proof stage for temporal investigation:
    /// "blocked" | "triaging" | "proving" | "ready_to_edit".
    pub proof_state: String,
    pub changes: Vec<TimelineChange>,
    pub co_changed_with: Vec<CoChangePartner>,
    /// "accelerating" | "decelerating" | "stable"
    pub velocity: String,
    /// [0.0, 1.0] — 1.0 = very stable, 0.0 = very volatile.
    pub stability_score: f32,
    /// "expanding" | "shrinking" | "churning" | "dormant" | "stable"
    pub pattern: String,
    pub total_churn: ChurnSummary,
    pub commit_count_in_window: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_tool: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_target: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_step_hint: Option<String>,
    pub elapsed_ms: f64,
}

#[derive(Clone, Debug, Serialize)]
pub struct TimelineChange {
    pub date: String,
    pub commit: String,
    pub author: String,
    pub subject: String,
    /// "+45/-12" format.
    pub delta: String,
    pub co_changed: Vec<String>,
}

#[derive(Clone, Debug, Serialize)]
pub struct CoChangePartner {
    pub file: String,
    pub times: u32,
    /// co_changes(A,B) / max(changes(A), changes(B)). [0.0, 1.0].
    pub coupling_degree: f32,
}

#[derive(Clone, Debug, Serialize)]
pub struct ChurnSummary {
    pub lines_added: u32,
    pub lines_deleted: u32,
}

// ---------------------------------------------------------------------------
// m1nd.diverge (L3-TEMPORAL-INTELLIGENCE §6)
// ---------------------------------------------------------------------------

/// Input for m1nd.diverge — structural drift between two points in time.
/// Compares graph state at baseline vs current.
#[derive(Clone, Debug, Deserialize)]
pub struct DivergeInput {
    pub agent_id: String,
    /// Baseline reference: ISO date ("2026-03-01"), git ref (SHA/tag),
    /// or "last_session" to use the saved GraphFingerprint.
    pub baseline: String,
    /// File path glob to limit scope. None = all nodes.
    #[serde(default)]
    pub scope: Option<String>,
    /// Include coupling matrix delta. Default: true.
    #[serde(default = "default_true")]
    pub include_coupling_changes: bool,
    /// Detect anomalies (test deficits, velocity spikes). Default: true.
    #[serde(default = "default_true")]
    pub include_anomalies: bool,
}

/// Output for m1nd.diverge.
#[derive(Clone, Debug, Serialize)]
pub struct DivergeOutput {
    pub baseline: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub baseline_commit: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
    /// 1.0 - jaccard(baseline_nodes, current_nodes). [0.0, 1.0].
    pub structural_drift: f32,
    pub new_nodes: Vec<String>,
    pub removed_nodes: Vec<String>,
    pub modified_nodes: Vec<DivergeModifiedNode>,
    pub coupling_changes: Vec<CouplingChange>,
    pub anomalies: Vec<DivergeAnomaly>,
    pub summary: String,
    pub elapsed_ms: f64,
}

#[derive(Clone, Debug, Serialize)]
pub struct DivergeModifiedNode {
    pub file: String,
    /// "+450/-30" format.
    pub delta: String,
    pub growth_ratio: f32,
}

#[derive(Clone, Debug, Serialize)]
pub struct CouplingChange {
    pub pair: [String; 2],
    pub was: f32,
    pub now: f32,
    /// "new_coupling" | "decoupled" | "strengthened" | "weakened"
    pub direction: String,
}

#[derive(Clone, Debug, Serialize)]
pub struct DivergeAnomaly {
    /// "test_deficit" | "velocity_spike" | "new_coupling" | "isolation"
    #[serde(rename = "type")]
    pub anomaly_type: String,
    pub file: String,
    pub detail: String,
    /// "critical" | "warning" | "info"
    pub severity: String,
}

// =========================================================================
// L4: Investigation Memory — m1nd.trail.*
// =========================================================================

// ---------------------------------------------------------------------------
// m1nd.trail.save (L4-INVESTIGATION-MEMORY §3, §4)
// ---------------------------------------------------------------------------

/// Input for m1nd.trail.save — persist the current investigation state.
/// Visited nodes are auto-captured from perspective + trail boosts.
#[derive(Clone, Debug, Deserialize)]
pub struct TrailSaveInput {
    pub agent_id: String,
    /// Human-readable label for this investigation.
    pub label: String,
    /// Hypotheses formed during investigation.
    #[serde(default)]
    pub hypotheses: Vec<TrailHypothesisInput>,
    /// Conclusions reached.
    #[serde(default)]
    pub conclusions: Vec<TrailConclusionInput>,
    /// Open questions remaining.
    #[serde(default)]
    pub open_questions: Vec<String>,
    /// Tags for organization and search.
    #[serde(default)]
    pub tags: Vec<String>,
    /// Optional summary. Auto-generated if omitted.
    #[serde(default)]
    pub summary: Option<String>,
    /// Optional: explicitly list visited node external_ids with annotations.
    /// If omitted, captured from active perspective state.
    #[serde(default)]
    pub visited_nodes: Vec<TrailVisitedNodeInput>,
    /// Optional: activation boosts to re-inject on resume.
    /// Map of node_external_id -> boost weight [0.0, 1.0].
    #[serde(default)]
    pub activation_boosts: HashMap<String, f32>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct TrailHypothesisInput {
    pub statement: String,
    #[serde(default = "default_confidence")]
    pub confidence: f32,
    #[serde(default)]
    pub supporting_nodes: Vec<String>,
    #[serde(default)]
    pub contradicting_nodes: Vec<String>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct TrailConclusionInput {
    pub statement: String,
    #[serde(default = "default_confidence")]
    pub confidence: f32,
    #[serde(default)]
    pub from_hypotheses: Vec<String>,
    #[serde(default)]
    pub supporting_nodes: Vec<String>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct TrailVisitedNodeInput {
    pub node_external_id: String,
    #[serde(default)]
    pub annotation: Option<String>,
    #[serde(default = "default_relevance")]
    pub relevance: f32,
}

/// Output for m1nd.trail.save.
#[derive(Clone, Debug, Serialize)]
pub struct TrailSaveOutput {
    pub trail_id: String,
    pub label: String,
    pub agent_id: String,
    pub nodes_saved: usize,
    pub hypotheses_saved: usize,
    pub conclusions_saved: usize,
    pub open_questions_saved: usize,
    pub graph_generation_at_creation: u64,
    pub created_at_ms: u64,
}

// ---------------------------------------------------------------------------
// m1nd.trail.resume (L4-INVESTIGATION-MEMORY §5)
// ---------------------------------------------------------------------------

/// Input for m1nd.trail.resume — restore a saved investigation.
/// Re-injects activation boosts, validates node existence, detects staleness.
#[derive(Clone, Debug, Deserialize)]
pub struct TrailResumeInput {
    pub agent_id: String,
    pub trail_id: String,
    /// Resume even if trail is stale (>50% missing nodes). Default: false.
    #[serde(default)]
    pub force: bool,
    /// Max reactivated node previews to return. Default: 5.
    #[serde(default = "default_top_k_5")]
    pub max_reactivated_nodes: usize,
    /// Max resume hints to return. Default: 4.
    #[serde(default = "default_top_k_4")]
    pub max_resume_hints: usize,
}

/// Output for m1nd.trail.resume.
#[derive(Clone, Debug, Serialize)]
pub struct TrailResumeOutput {
    pub trail_id: String,
    pub label: String,
    /// Whether the trail was stale (graph changed since save).
    pub stale: bool,
    /// Number of graph generations behind.
    pub generations_behind: u64,
    /// Nodes from trail that no longer exist in the graph.
    pub missing_nodes: Vec<String>,
    /// Number of nodes successfully re-activated via boost injection.
    pub nodes_reactivated: usize,
    /// Preview of the strongest nodes reactivated into the graph state.
    pub reactivated_node_ids: Vec<String>,
    /// Hypotheses that were downgraded due to missing supporting nodes.
    pub hypotheses_downgraded: Vec<String>,
    /// Strongest node to continue investigating next, if one is available.
    pub next_focus_node_id: Option<String>,
    /// Highest-priority open question carried forward from the saved trail.
    pub next_open_question: Option<String>,
    /// Suggested next tool for continuing the investigation.
    pub next_suggested_tool: Option<String>,
    /// Suggested next prompts or moves for continuing the investigation.
    pub resume_hints: Vec<String>,
    /// The full trail data.
    pub trail: TrailSummaryOutput,
    pub elapsed_ms: f64,
}

/// Compact trail representation in outputs.
#[derive(Clone, Debug, Serialize)]
pub struct TrailSummaryOutput {
    pub trail_id: String,
    pub agent_id: String,
    pub label: String,
    /// "active" | "saved" | "archived" | "stale" | "merged"
    pub status: String,
    pub created_at_ms: u64,
    pub last_modified_ms: u64,
    pub node_count: usize,
    pub hypothesis_count: usize,
    pub conclusion_count: usize,
    pub open_question_count: usize,
    pub tags: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
}

// ---------------------------------------------------------------------------
// m1nd.trail.merge (L4-INVESTIGATION-MEMORY §6)
// ---------------------------------------------------------------------------

/// Input for m1nd.trail.merge — combine two or more investigation trails.
/// Uses confidence+recency scoring for conflict resolution.
#[derive(Clone, Debug, Deserialize)]
pub struct TrailMergeInput {
    pub agent_id: String,
    /// Two or more trail IDs to merge.
    pub trail_ids: Vec<String>,
    /// Label for the merged trail. Auto-generated if omitted.
    #[serde(default)]
    pub label: Option<String>,
}

/// Output for m1nd.trail.merge.
#[derive(Clone, Debug, Serialize)]
pub struct TrailMergeOutput {
    pub merged_trail_id: String,
    pub label: String,
    /// Source trail IDs that were merged (now status = "merged").
    pub source_trails: Vec<String>,
    pub nodes_merged: usize,
    pub hypotheses_merged: usize,
    /// Hypothesis conflicts detected during merge.
    pub conflicts: Vec<TrailMergeConflict>,
    /// Connections discovered between the two independently explored areas.
    pub connections_discovered: Vec<TrailConnection>,
    pub elapsed_ms: f64,
}

#[derive(Clone, Debug, Serialize)]
pub struct TrailMergeConflict {
    pub hypothesis_a: String,
    pub hypothesis_b: String,
    /// "resolved" (one won) or "unresolved" (flagged for human review).
    pub resolution: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub winner: Option<String>,
    pub score_delta: f32,
}

#[derive(Clone, Debug, Serialize)]
pub struct TrailConnection {
    /// "shared_node" | "bridge_edge" | "cross_support"
    #[serde(rename = "type")]
    pub connection_type: String,
    pub detail: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_node: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to_node: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub weight: Option<f32>,
}

// ---------------------------------------------------------------------------
// m1nd.trail.list (L4-INVESTIGATION-MEMORY §8.2)
// ---------------------------------------------------------------------------

/// Input for m1nd.trail.list — list trails matching filters.
#[derive(Clone, Debug, Deserialize)]
pub struct TrailListInput {
    pub agent_id: String,
    /// Filter to a specific agent's trails. None = all agents.
    #[serde(default)]
    pub filter_agent_id: Option<String>,
    /// Filter by status: "active", "saved", "archived", "stale", "merged".
    #[serde(default)]
    pub filter_status: Option<String>,
    /// Filter by tags (any match).
    #[serde(default)]
    pub filter_tags: Vec<String>,
}

/// Output for m1nd.trail.list.
#[derive(Clone, Debug, Serialize)]
pub struct TrailListOutput {
    pub trails: Vec<TrailSummaryOutput>,
    pub total_count: usize,
}

// =========================================================================
// L5: Hypothesis Engine — m1nd.hypothesize + m1nd.differential
// =========================================================================

// ---------------------------------------------------------------------------
// m1nd.hypothesize (L5-HYPOTHESIS-ENGINE §2, §3, §4)
// ---------------------------------------------------------------------------

/// Input for m1nd.hypothesize — test a structural claim about the codebase.
/// Encodes the claim as a graph query and returns evidence for/against.
///
/// Supported claim patterns (auto-detected from natural language):
///   NEVER_CALLS, ALWAYS_BEFORE, DEPENDS_ON, NO_DEPENDENCY,
///   COUPLING, ISOLATED, GATEWAY, CIRCULAR
#[derive(Clone, Debug, Deserialize)]
pub struct HypothesizeInput {
    /// Natural language claim about the codebase.
    /// Examples:
    ///   "chat_handler never validates session tokens"
    ///   "all external calls go through smart_router"
    ///   "critic is independent of whatsapp"
    pub claim: String,
    pub agent_id: String,
    /// Max BFS hops for evidence search. Default: 5.
    #[serde(default = "default_max_hops")]
    pub max_hops: u8,
    /// Whether to include ghost edges as weak evidence. Default: true.
    #[serde(default = "default_true")]
    pub include_ghost_edges: bool,
    /// Whether to include partial flow when full path not found. Default: true.
    #[serde(default = "default_true")]
    pub include_partial_flow: bool,
    /// Budget cap for all-paths enumeration. Default: 1000.
    #[serde(default = "default_path_budget")]
    pub path_budget: usize,
}

/// Output for m1nd.hypothesize.
#[derive(Clone, Debug, Serialize)]
pub struct HypothesizeOutput {
    pub claim: String,
    /// Parsed claim type: "never_calls", "always_before", "depends_on",
    /// "no_dependency", "coupling", "isolated", "gateway", "circular".
    pub claim_type: String,
    /// Resolved subject node(s).
    pub subject_nodes: Vec<String>,
    /// Resolved object/target node(s).
    pub object_nodes: Vec<String>,
    /// "likely_true" (>0.8), "likely_false" (<0.2), or "inconclusive".
    pub verdict: String,
    /// Bayesian posterior confidence [0.01, 0.99].
    pub confidence: f32,
    /// Coarse proof stage for agent orchestration:
    /// "blocked" | "triaging" | "proving" | "ready_to_edit".
    pub proof_state: String,
    pub supporting_evidence: Vec<HypothesisEvidence>,
    pub contradicting_evidence: Vec<HypothesisEvidence>,
    /// Partial flow: how far the search reached before stopping.
    /// Only populated when full path was not found.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub partial_reach: Option<Vec<PartialReachEntry>>,
    pub paths_explored: usize,
    pub elapsed_ms: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_tool: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_target: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_step_hint: Option<String>,
}

/// A single piece of evidence for or against a hypothesis.
#[derive(Clone, Debug, Serialize)]
pub struct HypothesisEvidence {
    /// "path_found" | "no_path" | "ghost_edge" | "community_membership" |
    /// "causal_chain" | "counterfactual_impact" | "activation_reach"
    #[serde(rename = "type")]
    pub evidence_type: String,
    pub description: String,
    /// Likelihood factor contributed by this evidence.
    pub likelihood_factor: f32,
    /// Node IDs involved in this evidence.
    pub nodes: Vec<String>,
    /// Edge relations along the evidence path (if path-based).
    #[serde(default)]
    pub relations: Vec<String>,
    /// Total edge weight along the path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path_weight: Option<f32>,
}

#[derive(Clone, Debug, Serialize)]
pub struct PartialReachEntry {
    pub node_id: String,
    pub label: String,
    pub hops_from_source: u8,
    pub activation_at_stop: f32,
}

// ---------------------------------------------------------------------------
// m1nd.differential (L5-HYPOTHESIS-ENGINE §5)
// ---------------------------------------------------------------------------

/// Input for m1nd.differential — focused structural diff between two
/// graph snapshots.
#[derive(Clone, Debug, Deserialize)]
pub struct DifferentialInput {
    pub agent_id: String,
    /// Path to snapshot A, or "current" for the in-memory graph.
    pub snapshot_a: String,
    /// Path to snapshot B, or "current" for the in-memory graph.
    pub snapshot_b: String,
    /// Focus filter question. Narrows the diff output.
    /// Examples: "what new coupling was introduced?",
    ///           "what modules became isolated?"
    #[serde(default)]
    pub question: Option<String>,
    /// Optional: limit diff to neighborhood of specific nodes.
    #[serde(default)]
    pub focus_nodes: Vec<String>,
}

/// Output for m1nd.differential.
#[derive(Clone, Debug, Serialize)]
pub struct DifferentialOutput {
    pub snapshot_a: String,
    pub snapshot_b: String,
    pub new_edges: Vec<DiffEdgeDelta>,
    pub removed_edges: Vec<DiffEdgeDelta>,
    pub weight_changes: Vec<DiffWeightDelta>,
    pub new_nodes: Vec<String>,
    pub removed_nodes: Vec<String>,
    pub coupling_deltas: Vec<DiffCouplingDelta>,
    pub summary: String,
    pub elapsed_ms: f64,
}

#[derive(Clone, Debug, Serialize)]
pub struct DiffEdgeDelta {
    pub source: String,
    pub target: String,
    pub relation: String,
    pub weight: f32,
}

#[derive(Clone, Debug, Serialize)]
pub struct DiffWeightDelta {
    pub source: String,
    pub target: String,
    pub relation: String,
    pub old_weight: f32,
    pub new_weight: f32,
    pub delta: f32,
}

#[derive(Clone, Debug, Serialize)]
pub struct DiffCouplingDelta {
    pub community_a: String,
    pub community_b: String,
    pub old_coupling: f32,
    pub new_coupling: f32,
    pub delta: f32,
}

// =========================================================================
// L6: Execution Feedback — m1nd.trace + m1nd.validate_plan
// =========================================================================

// ---------------------------------------------------------------------------
// m1nd.trace (L6-EXECUTION-FEEDBACK §4)
// ---------------------------------------------------------------------------

/// Input for m1nd.trace — map runtime errors to structural root causes.
/// Parses stacktraces, maps frames to graph nodes, scores suspiciousness.
#[derive(Clone, Debug, Deserialize)]
pub struct TraceInput {
    /// Full error output (stacktrace + error message).
    pub error_text: String,
    pub agent_id: String,
    /// Language hint: "python", "rust", "typescript", "javascript", "go".
    /// Auto-detected if omitted.
    #[serde(default)]
    pub language: Option<String>,
    /// Temporal window (hours) for co-change suspect scan. Default: 24.0.
    #[serde(default = "default_window_hours")]
    pub window_hours: f32,
    /// Max suspects to return. Default: 10.
    #[serde(default = "default_top_k_10")]
    pub top_k: usize,
}

/// Output for m1nd.trace.
#[derive(Clone, Debug, Serialize)]
pub struct TraceOutput {
    pub language_detected: String,
    pub error_type: String,
    pub error_message: String,
    pub frames_parsed: usize,
    /// How many frames matched graph nodes.
    pub frames_mapped: usize,
    /// Coarse proof stage for agent orchestration:
    /// "blocked" | "triaging" | "proving" | "ready_to_edit".
    pub proof_state: String,
    /// Ranked suspects: most likely root cause first.
    pub suspects: Vec<TraceSuspect>,
    /// Files modified in the same temporal window as the top suspect.
    pub co_change_suspects: Vec<TraceCoChangeSuspect>,
    /// Causal chain from suspected root cause to error site.
    pub causal_chain: Vec<String>,
    pub fix_scope: TraceFixScope,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_tool: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_target: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_step_hint: Option<String>,
    /// Frames that could not be mapped to graph nodes.
    pub unmapped_frames: Vec<TraceUnmappedFrame>,
    pub elapsed_ms: f64,
}

#[derive(Clone, Debug, Serialize)]
pub struct TraceSuspect {
    pub node_id: String,
    pub label: String,
    #[serde(rename = "type")]
    pub node_type: String,
    /// Composite suspiciousness [0.0, 1.0].
    pub suspiciousness: f32,
    pub signals: TraceSuspiciousnessSignals,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line_start: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line_end: Option<u32>,
    /// Who calls this suspect.
    pub related_callers: Vec<String>,
}

#[derive(Clone, Debug, Serialize)]
pub struct TraceSuspiciousnessSignals {
    /// 1.0 = deepest frame; decays linearly.
    pub trace_depth_score: f32,
    /// Exponential decay from last modification time.
    pub recency_score: f32,
    /// Normalized PageRank centrality.
    pub centrality_score: f32,
}

#[derive(Clone, Debug, Serialize)]
pub struct TraceCoChangeSuspect {
    pub node_id: String,
    pub label: String,
    /// Unix timestamp of last modification.
    pub modified_at: f64,
    /// "Modified within Nh of top suspect".
    pub reason: String,
}

#[derive(Clone, Debug, Serialize)]
pub struct TraceFixScope {
    pub files_to_inspect: Vec<String>,
    pub estimated_blast_radius: usize,
    /// "low" | "medium" | "high" | "critical"
    pub risk_level: String,
}

#[derive(Clone, Debug, Serialize)]
pub struct TraceUnmappedFrame {
    pub file: String,
    pub line: u32,
    pub function: String,
    /// "file not in graph" | "line outside any node range" | "stdlib/third-party"
    pub reason: String,
}

// ---------------------------------------------------------------------------
// m1nd.validate_plan (L6-EXECUTION-FEEDBACK §5)
// ---------------------------------------------------------------------------

/// Input for m1nd.validate_plan — validate a proposed modification plan
/// against the code graph. Detects gaps, risk, and missing test coverage.
#[derive(Clone, Debug, Deserialize)]
pub struct ValidatePlanInput {
    pub agent_id: String,
    /// Ordered list of planned actions.
    pub actions: Vec<PlannedAction>,
    /// Whether to analyze test coverage for modified files. Default: true.
    #[serde(default = "default_true")]
    pub include_test_impact: bool,
    /// Whether to compute composite risk score. Default: true.
    #[serde(default = "default_true")]
    pub include_risk_score: bool,
}

/// A single action in a modification plan.
#[derive(Clone, Debug, Deserialize)]
pub struct PlannedAction {
    /// "modify" | "create" | "delete" | "rename" | "test"
    pub action_type: String,
    /// Relative file path.
    pub file_path: String,
    #[serde(default)]
    pub description: Option<String>,
    /// Other file_paths this action depends on.
    #[serde(default)]
    pub depends_on: Vec<String>,
}

/// Output for m1nd.validate_plan.
#[derive(Clone, Debug, Serialize)]
pub struct ValidatePlanOutput {
    pub actions_analyzed: usize,
    /// Matched to graph nodes.
    pub actions_resolved: usize,
    /// New files not yet in graph.
    pub actions_unresolved: usize,
    /// Files affected but not in the plan.
    pub gaps: Vec<PlanGap>,
    /// Composite risk [0.0, 1.0].
    pub risk_score: f32,
    /// "low" (<0.3) | "medium" (<0.6) | "high" (<0.8) | "critical" (>=0.8)
    pub risk_level: String,
    /// Coarse proof stage for agent orchestration:
    /// "blocked" | "triaging" | "proving" | "ready_to_edit".
    pub proof_state: String,
    pub test_coverage: PlanTestCoverage,
    /// Suggested additions to the plan.
    pub suggested_additions: Vec<PlanSuggestedAction>,
    pub blast_radius_total: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub heuristic_summary: Option<PlanHeuristicSummary>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_tool: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_target: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_step_hint: Option<String>,
    pub elapsed_ms: f64,
}

#[derive(Clone, Debug, Serialize)]
pub struct PlanGap {
    pub file_path: String,
    pub node_id: String,
    /// "imported by modified file X" | "in blast radius of Y"
    pub reason: String,
    /// "critical" | "warning" | "info"
    pub severity: String,
    pub signal_strength: f32,
    pub antibody_hits: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub heuristic_signals: Option<HeuristicSignals>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub heuristics_surface_ref: Option<HeuristicsSurfaceRef>,
}

#[derive(Clone, Debug, Serialize)]
pub struct PlanTestCoverage {
    pub modified_files: usize,
    pub tested_files: usize,
    pub untested_files: Vec<String>,
    pub coverage_ratio: f32,
}

#[derive(Clone, Debug, Serialize)]
pub struct PlanSuggestedAction {
    /// "modify" | "test"
    pub action_type: String,
    pub file_path: String,
    pub reason: String,
}

#[derive(Clone, Debug, Serialize)]
pub struct PlanHeuristicSummary {
    pub heuristic_risk: f32,
    pub hotspot_count: usize,
    pub low_trust_hotspots: usize,
    pub tremor_hotspots: usize,
    pub antibody_hotspots: usize,
    pub hotspots: Vec<PlanHeuristicHotspot>,
}

#[derive(Clone, Debug, Serialize)]
pub struct PlanHeuristicHotspot {
    pub file_path: String,
    pub node_id: String,
    /// "planned" | "gap"
    pub role: String,
    pub antibody_hits: usize,
    pub proof_hint: String,
    pub heuristic_signals: HeuristicSignals,
    pub heuristics_surface_ref: HeuristicsSurfaceRef,
}

#[derive(Clone, Debug, Serialize)]
pub struct HeuristicsSurfaceRef {
    pub node_id: String,
    pub file_path: String,
}

// =========================================================================
// L7: Multi-Repository Federation — m1nd.federate
// =========================================================================

// ---------------------------------------------------------------------------
// m1nd.federate (L7-MULTI-REPO-FEDERATION §6.3)
// ---------------------------------------------------------------------------

/// Input for m1nd.federate — ingest multiple repositories into a unified
/// federated graph with cross-repo edge detection.
///
/// Node IDs in the federated graph use `{repo_name}::file::path` format.
/// All existing query tools (activate, impact, why, etc.) traverse
/// cross-repo edges automatically.
#[derive(Clone, Debug, Deserialize)]
pub struct FederateInput {
    pub agent_id: String,
    /// List of repositories to federate.
    pub repos: Vec<FederateRepo>,
    /// Auto-detect cross-repo edges (config, API, import, type, deployment).
    /// Default: true.
    #[serde(default = "default_true")]
    pub detect_cross_repo_edges: bool,
    /// Only re-ingest repos that changed since last federation. Default: false.
    #[serde(default)]
    pub incremental: bool,
}

/// A single repository in a federation request.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FederateRepo {
    /// Repository name (used as namespace prefix in external_ids).
    pub name: String,
    /// Absolute path to repository root.
    pub path: String,
    /// Ingest adapter override. Default: "code".
    #[serde(default = "default_adapter")]
    pub adapter: String,
}

/// Output for m1nd.federate.
#[derive(Clone, Debug, Serialize)]
pub struct FederateOutput {
    pub repos_ingested: Vec<FederateRepoResult>,
    pub total_nodes: u32,
    pub total_edges: u64,
    pub cross_repo_edges: Vec<FederateCrossRepoEdge>,
    pub cross_repo_edge_count: usize,
    /// Whether incremental mode was used.
    pub incremental: bool,
    /// Repos that were skipped (unchanged) in incremental mode.
    pub skipped_repos: Vec<String>,
    pub elapsed_ms: f64,
}

/// Per-repo ingestion result in federation.
#[derive(Clone, Debug, Serialize)]
pub struct FederateRepoResult {
    pub name: String,
    pub path: String,
    pub node_count: u32,
    pub edge_count: u32,
    /// Whether this repo was freshly ingested or loaded from cache.
    pub from_cache: bool,
    pub ingest_ms: f64,
}

/// A detected cross-repo edge.
#[derive(Clone, Debug, Serialize)]
pub struct FederateCrossRepoEdge {
    pub source_repo: String,
    pub target_repo: String,
    pub source_node: String,
    pub target_node: String,
    /// "shared_config" | "api_contract" | "package_dep" | "shared_type" |
    /// "deployment_dep" | "mcp_contract"
    pub edge_type: String,
    pub relation: String,
    pub weight: f32,
    pub causal_strength: f32,
}

// =========================================================================
// RETROBUILDER Modules — ghost_edges / taint_trace / twins / refactor_plan / runtime_overlay
// =========================================================================

// ---------------------------------------------------------------------------
// m1nd.ghost_edges (RB-01: 4D Git Graph)
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct GhostEdgesInput {
    pub agent_id: String,
    /// Depth of git history: "7d", "30d", "90d", "all". Default: "30d".
    #[serde(default = "default_depth_30d")]
    pub depth: String,
    /// Scope filter: only process files matching this prefix.
    #[serde(default)]
    pub scope: Option<String>,
    /// Maximum ghost edges to return. Default: 50.
    #[serde(default = "default_scan_limit")]
    pub top_k: usize,
}

// ---------------------------------------------------------------------------
// m1nd.taint_trace (RB-02: Graph Fuzzing / Taint Propagation)
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct TaintTraceInput {
    pub agent_id: String,
    /// Entry point node IDs to inject taint.
    pub entry_nodes: Vec<String>,
    /// Taint type: "user_input", "sensitive_data", or custom boundary patterns.
    #[serde(default = "default_taint_type")]
    pub taint_type: String,
    /// Custom boundary patterns (used when taint_type = "custom").
    #[serde(default)]
    pub boundary_patterns: Vec<String>,
    /// Maximum propagation depth. Default: 15.
    #[serde(default = "default_taint_max_depth")]
    pub max_depth: u32,
    /// Minimum infection probability to report. Default: 0.01.
    #[serde(default = "default_taint_min_prob")]
    pub min_probability: f32,
}

fn default_taint_type() -> String {
    "user_input".to_string()
}
fn default_taint_max_depth() -> u32 {
    15
}
fn default_taint_min_prob() -> f32 {
    0.01
}

// ---------------------------------------------------------------------------
// m1nd.twins (RB-03: Structural Twins)
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct TwinsInput {
    pub agent_id: String,
    /// Minimum cosine similarity threshold [0.0, 1.0]. Default: 0.80.
    #[serde(default = "default_twin_threshold")]
    pub similarity_threshold: f32,
    /// Maximum twin pairs to return. Default: 50.
    #[serde(default = "default_scan_limit")]
    pub top_k: usize,
    /// File path prefix to limit scope.
    #[serde(default)]
    pub scope: Option<String>,
    /// Node type filter (empty = all).
    #[serde(default)]
    pub node_types: Vec<String>,
}

fn default_twin_threshold() -> f32 {
    0.80
}

// ---------------------------------------------------------------------------
// m1nd.refactor_plan (RB-04: Intent-Driven Refactoring)
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct RefactorPlanInput {
    pub agent_id: String,
    /// File path prefix to limit scope. Narrows community detection to this area.
    #[serde(default)]
    pub scope: Option<String>,
    /// Maximum communities to consider. Default: 10.
    #[serde(default = "default_max_communities")]
    pub max_communities: usize,
    /// Minimum nodes for a community to be extractable. Default: 3.
    #[serde(default = "default_min_community_size")]
    pub min_community_size: usize,
}

fn default_max_communities() -> usize {
    10
}
fn default_min_community_size() -> usize {
    3
}

// ---------------------------------------------------------------------------
// m1nd.runtime_overlay (RB-05: OpenTelemetry Overlay)
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct RuntimeOverlayInput {
    pub agent_id: String,
    /// OTel spans to ingest.
    pub spans: Vec<RuntimeOverlaySpan>,
    /// Service name for scoping.
    #[serde(default)]
    pub service_name: String,
    /// Mapping strategy: "label_match", "code_attribute", "exact_id".
    #[serde(default = "default_mapping_strategy")]
    pub mapping_strategy: String,
    /// Activation boost strength [0.0, 1.0]. Default: 0.15.
    #[serde(default = "default_boost_strength")]
    pub boost_strength: f32,
}

#[derive(Clone, Debug, Deserialize)]
pub struct RuntimeOverlaySpan {
    pub name: String,
    pub duration_us: u64,
    #[serde(default = "default_span_count")]
    pub count: u64,
    #[serde(default)]
    pub is_error: bool,
    #[serde(default)]
    pub attributes: std::collections::HashMap<String, String>,
    pub parent: Option<String>,
}

fn default_mapping_strategy() -> String {
    "label_match".to_string()
}
fn default_boost_strength() -> f32 {
    0.15
}
fn default_span_count() -> u64 {
    1
}

// =========================================================================
// Default value helpers
// =========================================================================

fn default_top_k() -> usize {
    20
}
fn default_top_k_5() -> usize {
    5
}
fn default_top_k_4() -> usize {
    4
}
fn default_top_k_10() -> usize {
    10
}
fn default_true() -> bool {
    true
}
fn default_max_hops() -> u8 {
    5
}
fn default_min_score() -> f32 {
    0.1
}
fn default_severity_min() -> f32 {
    0.3
}
fn default_scan_limit() -> usize {
    50
}
fn default_depth_30d() -> String {
    "30d".into()
}
fn default_confidence() -> f32 {
    0.5
}
fn default_relevance() -> f32 {
    0.5
}
fn default_path_budget() -> usize {
    1000
}
fn default_window_hours() -> f32 {
    24.0
}
fn default_adapter() -> String {
    "code".into()
}

// =========================================================================
// Superpowers — Antibody / Flow / Epidemic / Tremor / Trust / Layers
// =========================================================================

// ---------------------------------------------------------------------------
// m1nd.antibody_scan
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct AntibodyScanInput {
    pub agent_id: String,
    #[serde(default = "default_scope_all")]
    pub scope: String,
    #[serde(default)]
    pub antibody_ids: Vec<String>,
    #[serde(default = "default_scan_limit")]
    pub max_matches: usize,
    #[serde(default = "default_severity_info")]
    pub min_severity: String,
    /// Fuzzy match threshold for label matching (0.0-1.0, default 0.7).
    #[serde(default = "default_similarity_threshold")]
    pub similarity_threshold: f32,
    /// Match mode for label comparison: "exact", "substring", "regex" (default "substring").
    #[serde(default = "default_match_mode")]
    pub match_mode: String,
    /// Maximum matches per individual antibody (default 50).
    #[serde(default = "default_max_matches_per_antibody")]
    pub max_matches_per_antibody: usize,
}

fn default_scope_all() -> String {
    "all".to_string()
}
fn default_severity_info() -> String {
    "info".to_string()
}
fn default_similarity_threshold() -> f32 {
    0.7
}
fn default_match_mode() -> String {
    "substring".to_string()
}
fn default_max_matches_per_antibody() -> usize {
    50
}

// ---------------------------------------------------------------------------
// m1nd.antibody_list
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct AntibodyListInput {
    pub agent_id: String,
    #[serde(default)]
    pub include_disabled: bool,
}

// ---------------------------------------------------------------------------
// m1nd.antibody_create
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct AntibodyCreateInput {
    pub agent_id: String,
    #[serde(default = "default_action_create")]
    pub action: String,
    pub antibody_id: Option<String>,
    pub name: Option<String>,
    pub description: Option<String>,
    #[serde(default = "default_severity_warning")]
    pub severity: String,
    pub pattern: Option<AntibodyPatternInput>,
}

fn default_action_create() -> String {
    "create".to_string()
}
fn default_severity_warning() -> String {
    "warning".to_string()
}

#[derive(Clone, Debug, Deserialize)]
pub struct AntibodyPatternInput {
    pub nodes: Vec<PatternNodeInput>,
    pub edges: Vec<PatternEdgeInput>,
    #[serde(default)]
    pub negative_edges: Vec<PatternEdgeInput>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct PatternNodeInput {
    pub role: String,
    pub node_type: Option<String>,
    #[serde(default)]
    pub required_tags: Vec<String>,
    pub label_contains: Option<String>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct PatternEdgeInput {
    pub source_idx: usize,
    pub target_idx: usize,
    pub relation: Option<String>,
}

// ---------------------------------------------------------------------------
// m1nd.flow_simulate
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct FlowSimulateInput {
    pub agent_id: String,
    #[serde(default)]
    pub entry_nodes: Vec<String>,
    #[serde(default = "default_num_particles")]
    pub num_particles: u32,
    #[serde(default)]
    pub lock_patterns: Vec<String>,
    #[serde(default)]
    pub read_only_patterns: Vec<String>,
    #[serde(default = "default_flow_max_depth")]
    pub max_depth: u8,
    #[serde(default = "default_turbulence_threshold")]
    pub turbulence_threshold: f32,
    #[serde(default = "default_true")]
    pub include_paths: bool,
    /// Global step budget across all particles (default 50000).
    #[serde(default = "default_max_total_steps")]
    pub max_total_steps: usize,
    /// Regex to limit which nodes particles can enter (default: no filter).
    #[serde(default)]
    pub scope_filter: Option<String>,
}

fn default_num_particles() -> u32 {
    2
}
fn default_flow_max_depth() -> u8 {
    15
}
fn default_turbulence_threshold() -> f32 {
    0.5
}
fn default_max_total_steps() -> usize {
    50000
}

// ---------------------------------------------------------------------------
// m1nd.epidemic
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct EpidemicInput {
    pub agent_id: String,
    pub infected_nodes: Vec<String>,
    #[serde(default)]
    pub recovered_nodes: Vec<String>,
    pub infection_rate: Option<f32>,
    #[serde(default)]
    pub recovery_rate: f32,
    #[serde(default = "default_epidemic_iterations")]
    pub iterations: u32,
    #[serde(default = "default_direction_both")]
    pub direction: String,
    #[serde(default = "default_top_k")]
    pub top_k: usize,
    /// Auto-adjust infection_rate based on graph density (default true).
    #[serde(default = "default_true")]
    pub auto_calibrate: bool,
    /// Filter predictions to node types: "files", "functions", "all" (default "all").
    #[serde(default = "default_scope_all")]
    pub scope: String,
    /// Filter out predictions below this probability (default 0.001).
    #[serde(default = "default_min_probability")]
    pub min_probability: f32,
}

fn default_epidemic_iterations() -> u32 {
    50
}
fn default_direction_both() -> String {
    "both".to_string()
}
fn default_min_probability() -> f32 {
    0.001
}

// ---------------------------------------------------------------------------
// m1nd.tremor
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct TremorInput {
    pub agent_id: String,
    #[serde(default = "default_tremor_window")]
    pub window: String,
    #[serde(default = "default_tremor_threshold")]
    pub threshold: f32,
    #[serde(default = "default_top_k")]
    pub top_k: usize,
    pub node_filter: Option<String>,
    #[serde(default)]
    pub include_history: bool,
    /// Minimum data points to compute tremor (default 3).
    #[serde(default = "default_min_observations")]
    pub min_observations: usize,
    /// Multiplier on acceleration threshold (default 1.0).
    #[serde(default = "default_sensitivity")]
    pub sensitivity: f32,
}

fn default_tremor_window() -> String {
    "30d".to_string()
}
fn default_tremor_threshold() -> f32 {
    0.1
}
fn default_min_observations() -> usize {
    3
}
fn default_sensitivity() -> f32 {
    1.0
}

// ---------------------------------------------------------------------------
// m1nd.trust
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct TrustInput {
    pub agent_id: String,
    #[serde(default = "default_scope_file")]
    pub scope: String,
    #[serde(default = "default_min_history")]
    pub min_history: u32,
    #[serde(default = "default_top_k")]
    pub top_k: usize,
    pub node_filter: Option<String>,
    #[serde(default = "default_sort_trust_asc")]
    pub sort_by: String,
    /// How fast old defects lose weight, in days (default 30.0).
    #[serde(default = "default_decay_half_life_days")]
    pub decay_half_life_days: f32,
    /// Maximum risk multiplier cap (default 3.0).
    #[serde(default = "default_risk_cap")]
    pub risk_cap: f32,
}

fn default_scope_file() -> String {
    "file".to_string()
}
fn default_min_history() -> u32 {
    1
}
fn default_sort_trust_asc() -> String {
    "trust_asc".to_string()
}
fn default_decay_half_life_days() -> f32 {
    30.0
}
fn default_risk_cap() -> f32 {
    3.0
}

// ---------------------------------------------------------------------------
// m1nd.layers
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct LayersInput {
    pub agent_id: String,
    #[serde(default)]
    pub scope: Option<String>,
    #[serde(default = "default_max_layers")]
    pub max_layers: u8,
    #[serde(default = "default_true")]
    pub include_violations: bool,
    #[serde(default = "default_min_nodes_per_layer")]
    pub min_nodes_per_layer: u32,
    #[serde(default)]
    pub node_types: Vec<String>,
    /// Naming strategy: "auto", "path_prefix", "pagerank" (default "auto").
    #[serde(default = "default_naming_strategy")]
    pub naming_strategy: String,
    /// Exclude test files from layer detection (default false).
    #[serde(default)]
    pub exclude_tests: bool,
    /// Maximum violations to return (default 100).
    #[serde(default = "default_violation_limit")]
    pub violation_limit: usize,
}

fn default_max_layers() -> u8 {
    8
}
fn default_min_nodes_per_layer() -> u32 {
    2
}
fn default_naming_strategy() -> String {
    "auto".to_string()
}
fn default_violation_limit() -> usize {
    100
}

// ---------------------------------------------------------------------------
// m1nd.layer_inspect
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct LayerInspectInput {
    pub agent_id: String,
    pub level: u8,
    #[serde(default)]
    pub scope: Option<String>,
    #[serde(default = "default_true")]
    pub include_edges: bool,
    #[serde(default = "default_scan_limit")]
    pub top_k: usize,
}

// =========================================================================
// TEMPESTA — m1nd.surgical_context + m1nd.apply
// (ORACLE-TESTS golden test contracts — Step 7 of Grounded One-Shot Build)
// =========================================================================

// ---------------------------------------------------------------------------
// m1nd.surgical_context
//
// Returns a rich, surgery-ready view of a single graph node:
//   - source code peek (file content window around the node)
//   - callers + callees (direct neighbours by relation)
//   - blast radius (forward/backward impact count)
//   - trust score (actuarial defect rate from TrustLedger)
//
// Designed to give a builder agent EXACTLY what it needs to make a safe,
// targeted edit without having to call ingest + impact + peek separately.
// ---------------------------------------------------------------------------

/// Input for m1nd.surgical_context.
#[derive(Clone, Debug, Deserialize)]
pub struct SurgicalContextInput {
    /// External node ID or label to inspect.
    pub node_id: String,
    pub agent_id: String,
    /// Maximum source lines to return around the node's line range.
    /// Default: 200. Hard cap: 1000 (to prevent huge context blobs).
    #[serde(default = "default_surgical_max_lines")]
    pub max_lines: u32,
    /// Include callers (nodes that depend on this node). Default: true.
    #[serde(default = "default_true")]
    pub include_callers: bool,
    /// Include callees (nodes this node depends on). Default: true.
    #[serde(default = "default_true")]
    pub include_callees: bool,
    /// Include blast radius counts. Default: true.
    #[serde(default = "default_true")]
    pub include_blast_radius: bool,
    /// Include trust score from TrustLedger. Default: true.
    #[serde(default = "default_true")]
    pub include_trust_score: bool,
    /// Maximum callers/callees to return. Default: 20.
    #[serde(default = "default_surgical_max_deps")]
    pub max_deps: usize,
}

fn default_surgical_max_lines() -> u32 {
    200
}
fn default_surgical_max_deps() -> usize {
    20
}

/// Output for m1nd.surgical_context.
#[derive(Clone, Debug, Serialize)]
pub struct SurgicalContextOutput {
    /// The resolved external node ID.
    pub node_id: String,
    pub label: String,
    #[serde(rename = "type")]
    pub node_type: String,
    /// Source code peek (may be None if file not found or binary).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<SurgicalSourcePeek>,
    /// Nodes that call/import this node.
    pub callers: Vec<SurgicalDep>,
    /// Nodes that this node calls/imports.
    pub callees: Vec<SurgicalDep>,
    /// Number of nodes in the forward blast radius (nodes this affects).
    pub blast_radius_forward: usize,
    /// Number of nodes in the backward blast radius (nodes that affect this).
    pub blast_radius_backward: usize,
    /// Trust score [0.0, 1.0]; 1.0 = perfectly trustworthy, 0.0 = very risky.
    /// None if no defect history is recorded.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trust_score: Option<f32>,
    /// Whether the source file was modified after the last graph ingest.
    pub source_stale: bool,
    pub elapsed_ms: f64,
}

/// Source code window around a node.
#[derive(Clone, Debug, Serialize)]
pub struct SurgicalSourcePeek {
    pub file_path: String,
    /// Actual start line of the returned window (1-indexed).
    pub line_start: u32,
    /// Actual end line of the returned window (1-indexed).
    pub line_end: u32,
    /// The source text. May be truncated if `truncated` is true.
    pub content: String,
    /// True if the content was truncated due to `max_lines` or char cap.
    pub truncated: bool,
    /// True if file was modified since last ingest (provenance stale).
    pub stale: bool,
}

/// A single caller or callee dependency.
#[derive(Clone, Debug, Serialize)]
pub struct SurgicalDep {
    pub node_id: String,
    pub label: String,
    #[serde(rename = "type")]
    pub node_type: String,
    /// Relation type: "imports", "calls", "tests", etc.
    pub relation: String,
    /// Edge weight [0.0, 1.0].
    pub weight: f32,
}

// ---------------------------------------------------------------------------
// m1nd.apply
//
// Surgically write a line-range replacement into a source file and
// immediately re-ingest the file into the graph.
//
// Behaviour contract:
//   1. Validate the target path is within the project (no path traversal).
//   2. Verify the node exists in the graph and retrieve its provenance.
//   3. If the file has been modified since last ingest, return ApplyStaleError.
//   4. Write `new_content` to the file at [line_start, line_end].
//   5. Re-ingest the file (incremental merge).
//   6. Run m1nd.predict on the modified node.
//   7. Return the unified diff + predict results.
// ---------------------------------------------------------------------------

/// Input for m1nd.apply.
#[derive(Clone, Debug, Deserialize)]
pub struct ApplyInput {
    /// External node ID identifying the target file/function.
    pub node_id: String,
    pub agent_id: String,
    /// Absolute path to the file to write.
    pub file_path: String,
    /// Start line of the range to replace (1-indexed, inclusive).
    pub line_start: u32,
    /// End line of the range to replace (1-indexed, inclusive).
    pub line_end: u32,
    /// New content to write into [line_start, line_end].
    /// Lines NOT in this range are preserved.
    pub new_content: String,
    /// If true, abort if the file was modified since last ingest. Default: true.
    #[serde(default = "default_true")]
    pub fail_on_stale: bool,
    /// If true, run m1nd.predict after write and include results. Default: true.
    #[serde(default = "default_true")]
    pub include_predictions: bool,
    /// Top-K co-change predictions to include. Default: 5.
    #[serde(default = "default_apply_predict_k")]
    pub predict_top_k: usize,
}

fn default_apply_predict_k() -> usize {
    5
}

/// Output for m1nd.apply.
#[derive(Clone, Debug, Serialize)]
pub struct ApplyOutput {
    pub node_id: String,
    pub file_path: String,
    pub lines_replaced: u32,
    /// Unified diff of the change.
    pub diff: String,
    /// True if the graph was successfully re-ingested after write.
    pub graph_updated: bool,
    /// New node count after re-ingest.
    pub node_count: u32,
    /// Co-change predictions from the modified node.
    pub predictions: Vec<ApplyPrediction>,
    pub elapsed_ms: f64,
}

/// A single co-change prediction from m1nd.predict.
#[derive(Clone, Debug, Serialize)]
pub struct ApplyPrediction {
    pub node_id: String,
    pub label: String,
    /// Co-change likelihood [0.0, 1.0].
    pub likelihood: f32,
    pub reason: String,
}

// =========================================================================
// v0.4.0: m1nd.search — Literal/Regex Search
// =========================================================================

/// Search mode for m1nd.search.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum SearchMode {
    /// Exact substring match on node labels and source content.
    #[default]
    Literal,
    /// Regex pattern match on node labels and source content.
    Regex,
    /// Semantic trigram TF-IDF search (delegates to seek engine).
    Semantic,
}

/// Input for m1nd.search — unified literal/regex/semantic search.
/// v0.5.0: adds invert, count_only, multiline, auto_ingest, filename_pattern.
#[derive(Clone, Debug, Deserialize)]
pub struct SearchInput {
    pub agent_id: String,
    /// The search term: exact string, regex pattern, or natural language query.
    pub query: String,
    /// Search mode. Default: "literal".
    #[serde(default)]
    pub mode: SearchMode,
    /// Namespace / file path prefix to limit search scope. None = entire graph.
    #[serde(default)]
    pub scope: Option<String>,
    /// Maximum results to return. Default: 50.
    #[serde(default = "default_search_top_k")]
    pub top_k: u32,
    /// Case-sensitive matching for literal/regex modes. Default: false.
    #[serde(default)]
    pub case_sensitive: bool,
    /// Include N lines of context around each match. Default: 2.
    #[serde(default = "default_context_lines")]
    pub context_lines: u32,

    // --- v0.5.0 additions ---
    /// Return lines that DON'T match the query (grep -v). Default: false.
    /// Only applies to literal and regex modes in Phase 2 (file content search).
    #[serde(default)]
    pub invert: bool,
    /// Return just the match count, not the results themselves (grep -c). Default: false.
    /// When true, `results` will be empty and `match_count` holds the count.
    #[serde(default)]
    pub count_only: bool,
    /// Enable multiline regex matching (rg -U). Default: false.
    /// Only applies to regex mode. When true, '.' matches newlines
    /// and patterns can span multiple lines.
    #[serde(default)]
    pub multiline: bool,
    /// If `scope` resolves to exactly one path outside current ingest roots, ingest
    /// that path first so search can operate over the requested tree.
    /// Relative scopes are resolved against existing ingest roots (in order), then
    /// workspace_root. Ambiguous results return an error whose detail includes the
    /// candidate paths so the caller can refine scope.
    /// Default: false.
    #[serde(default)]
    pub auto_ingest: bool,
    /// Glob pattern to filter filenames (e.g. "*.rs", "test_*.py").
    /// Only files whose name matches this pattern will be searched.
    /// None = search all files in scope.
    #[serde(default)]
    pub filename_pattern: Option<String>,
    /// Optional cap for total returned characters across serialized matches.
    #[serde(default)]
    pub max_output_chars: Option<usize>,
}

fn default_search_top_k() -> u32 {
    50
}
fn default_context_lines() -> u32 {
    2
}

/// Output for m1nd.search.
/// v0.5.0: adds auto_ingested, match_count, auto_ingested_paths.
#[derive(Clone, Debug, Serialize)]
pub struct SearchOutput {
    pub query: String,
    pub mode: String,
    pub results: Vec<SearchResultEntry>,
    pub total_matches: usize,
    pub scope_applied: bool,
    pub elapsed_ms: f64,

    // --- v0.5.0 additions ---
    /// True if auto_ingest was triggered during this search.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub auto_ingested: bool,
    /// When count_only=true, this mirrors total_matches for clarity.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub match_count: Option<usize>,
    /// Paths that were auto-ingested (empty if auto_ingest was not triggered).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub auto_ingested_paths: Vec<String>,
    pub truncated: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inline_summary: Option<String>,
    pub proof_state: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_tool: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_target: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_step_hint: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub why_this_next_step: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub what_is_missing: Option<String>,
}

/// A single search result entry.
#[derive(Clone, Debug, Serialize)]
pub struct SearchResultEntry {
    pub node_id: String,
    pub label: String,
    #[serde(rename = "type")]
    pub node_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub score: Option<f32>,
    pub file_path: String,
    pub line_number: u32,
    /// The matched line text.
    pub matched_line: String,
    /// Lines before the match (up to context_lines).
    pub context_before: Vec<String>,
    /// Lines after the match (up to context_lines).
    pub context_after: Vec<String>,
    /// Whether the node_id is linked in the graph.
    pub graph_linked: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub heuristic_signals: Option<HeuristicSignals>,
}

// =========================================================================
// v0.4.0: m1nd.help — Self-Documenting Tool Help
// =========================================================================

/// Input for m1nd.help — runtime-discoverable documentation.
#[derive(Clone, Debug, Deserialize)]
pub struct HelpInput {
    pub agent_id: String,
    /// Tool name to look up (e.g. "activate", "m1nd.activate").
    /// When None, returns a compact index of all tools.
    #[serde(default)]
    pub tool_name: Option<String>,
}

/// Output for m1nd.help.
#[derive(Clone, Debug, Serialize)]
pub struct HelpOutput {
    /// Formatted string for terminal/chat display.
    /// Contains ANSI box-drawing, params, examples, and NEXT suggestions.
    pub formatted: String,
    /// Tool name that was looked up (None = full index).
    pub tool: Option<String>,
    /// Whether the tool was found (false = unknown_tool response with suggestions).
    pub found: bool,
    /// Suggested tools when tool was not found.
    #[serde(default)]
    pub suggestions: Vec<String>,
    pub proof_state: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_tool: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_target: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_step_hint: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub why_this_next_step: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub what_is_missing: Option<String>,
}

// =========================================================================
// v0.5.0: m1nd.glob — Graph-Aware File Glob
// =========================================================================

/// Input for m1nd.glob — find files in the graph by glob pattern.
/// Returns file paths matching the pattern from the ingested graph,
/// without touching the filesystem (zero I/O, pure graph query).
///
/// Examples:
///   glob("**/*.rs")                        -> all Rust files in graph
///   glob("src/**/test_*.py")               -> Python test files under src/
///   glob("backend/**/*.py", scope="api/")  -> Python files under backend/api/
#[derive(Clone, Debug, Deserialize)]
pub struct GlobInput {
    pub agent_id: String,
    /// Glob pattern to match against file paths in the graph.
    /// Supports: *, **, ?, [abc], {a,b}.
    pub pattern: String,
    /// Root directory prefix to narrow the glob scope.
    /// None = search entire graph.
    #[serde(default)]
    pub scope: Option<String>,
    /// Maximum results to return. Default: 200.
    #[serde(default = "default_glob_top_k")]
    pub top_k: u32,
    /// Sort order for results. Default: "path" (alphabetical).
    #[serde(default)]
    pub sort: GlobSort,
}

/// Sort order for glob results.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum GlobSort {
    /// Alphabetical by file path (default).
    #[default]
    Path,
    /// Highest graph activation score first.
    Activation,
}

fn default_glob_top_k() -> u32 {
    200
}

/// Output for m1nd.glob.
#[derive(Clone, Debug, Serialize)]
pub struct GlobOutput {
    /// The glob pattern that was matched.
    pub pattern: String,
    /// Matching file entries from the graph.
    pub files: Vec<GlobFileEntry>,
    /// Total files that matched (may exceed top_k).
    pub total_matches: usize,
    /// Whether scope prefix was applied.
    pub scope_applied: bool,
    pub elapsed_ms: f64,
    pub proof_state: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_tool: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_suggested_target: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_step_hint: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub why_this_next_step: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub what_is_missing: Option<String>,
}

/// A single file entry from a glob match.
#[derive(Clone, Debug, Serialize)]
pub struct GlobFileEntry {
    /// Graph node ID (e.g. "file::src/main.rs").
    pub node_id: String,
    /// Relative file path as stored in the graph.
    pub file_path: String,
    /// File extension (e.g. "rs", "py"). Empty for extensionless files.
    pub extension: String,
    /// Line count from graph metadata (0 if unknown).
    pub line_count: u32,
    /// Whether this file has outgoing edges to other files.
    pub has_connections: bool,
}

// =========================================================================
// v0.4.0: m1nd.report — Session Report
// =========================================================================

/// Input for m1nd.report — session usage and savings report.
#[derive(Clone, Debug, Deserialize)]
pub struct ReportInput {
    pub agent_id: String,
    #[serde(default)]
    pub max_output_chars: Option<usize>,
}

/// A query record in the session report.
#[derive(Clone, Debug, Serialize)]
pub struct ReportQueryEntry {
    pub tool: String,
    pub query: String,
    pub elapsed_ms: f64,
    /// Whether m1nd answered this query without grep/glob fallback.
    pub m1nd_answered: bool,
}

#[derive(Clone, Debug, Serialize)]
pub struct ReportHeuristicHotspot {
    pub node_id: String,
    pub file_path: String,
    pub risk_level: String,
    pub risk_score: f32,
    pub heuristic_signals: HeuristicSignals,
}

/// Output for m1nd.report — session statistics and token savings.
#[derive(Clone, Debug, Serialize)]
pub struct ReportOutput {
    pub agent_id: String,
    pub session_queries: u32,
    pub session_elapsed_ms: f64,
    /// Queries answered by m1nd in this session (not fallback to grep/glob).
    pub queries_answered: u32,
    /// Estimated tokens saved this session (based on avoided grep/glob ops).
    pub tokens_saved_session: u64,
    /// Estimated tokens saved globally (all sessions).
    pub tokens_saved_global: u64,
    /// CO2 grams saved (0.0002 g per avoided token).
    pub co2_saved_grams: f64,
    /// Recent query log (last 10).
    pub recent_queries: Vec<ReportQueryEntry>,
    /// Highest-risk heuristic hotspots visible in the current graph.
    pub heuristic_hotspots: Vec<ReportHeuristicHotspot>,
    /// Markdown-formatted summary for display.
    pub markdown_summary: String,
    pub truncated: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inline_summary: Option<String>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct ScanAllInput {
    pub agent_id: String,
    #[serde(default)]
    pub scope: Option<String>,
    #[serde(default = "default_severity_min")]
    pub severity_min: f32,
    #[serde(default = "default_true")]
    pub graph_validate: bool,
    #[serde(default = "default_scan_limit")]
    pub limit_per_pattern: usize,
    #[serde(default)]
    pub patterns: Vec<String>,
}

#[derive(Clone, Debug, Serialize)]
pub struct ScanAllPatternOutput {
    pub pattern: String,
    pub findings: Vec<ScanFinding>,
    pub files_scanned: usize,
    pub total_matches_raw: usize,
    pub total_matches_validated: usize,
}

#[derive(Clone, Debug, Serialize)]
pub struct ScanAllOutput {
    pub patterns_run: usize,
    pub total_findings: usize,
    pub by_pattern: Vec<ScanAllPatternOutput>,
    pub elapsed_ms: f64,
}

#[derive(Clone, Debug, Deserialize)]
pub struct CrossVerifyInput {
    pub agent_id: String,
    #[serde(default)]
    pub scope: Option<String>,
    #[serde(default)]
    pub check: Vec<String>,
    #[serde(default)]
    pub include_dotfiles: bool,
    #[serde(default)]
    pub dotfile_patterns: Vec<String>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct CoverageSessionInput {
    pub agent_id: String,
}

#[derive(Clone, Debug, Deserialize)]
pub struct ExternalReferencesInput {
    pub agent_id: String,
    #[serde(default)]
    pub scope: Option<String>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct FederateAutoInput {
    pub agent_id: String,
    #[serde(default)]
    pub scope: Option<String>,
    #[serde(default)]
    pub current_repo_name: Option<String>,
    #[serde(default = "default_federate_auto_max_repos")]
    pub max_repos: usize,
    #[serde(default = "default_true")]
    pub detect_cross_repo_edges: bool,
    #[serde(default)]
    pub execute: bool,
}

fn default_federate_auto_max_repos() -> usize {
    8
}

#[derive(Clone, Debug, Serialize)]
pub struct FederateAutoCurrentRepo {
    pub namespace: String,
    pub repo_root: String,
}

#[derive(Clone, Debug, Serialize)]
pub struct FederateAutoRepoCandidate {
    pub namespace: String,
    pub repo_root: String,
    pub marker: Option<String>,
    pub confidence: String,
    pub source_nodes: Vec<String>,
    pub source_files: Vec<String>,
    pub evidence_types: Vec<String>,
    pub sampled_paths: Vec<String>,
    pub suggested_action: String,
}

#[derive(Clone, Debug, Serialize)]
pub struct FederateAutoSkippedPath {
    pub external_path: String,
    pub reason: String,
    pub source_node: Option<String>,
    pub file_path: Option<String>,
}

#[derive(Clone, Debug, Serialize)]
pub struct FederateAutoOutput {
    pub current_repo: FederateAutoCurrentRepo,
    pub discovered_repos: Vec<FederateAutoRepoCandidate>,
    pub suggested_repos: Vec<FederateRepo>,
    pub skipped_paths: Vec<FederateAutoSkippedPath>,
    pub executed: bool,
    pub federate_result: Option<FederateOutput>,
    pub elapsed_ms: f64,
}

#[derive(Clone, Debug, Deserialize)]
pub struct AuditInput {
    pub agent_id: String,
    pub path: String,
    #[serde(default = "default_audit_profile")]
    pub profile: String,
    #[serde(default = "default_audit_depth")]
    pub depth: String,
    #[serde(default = "default_true")]
    pub cross_verify: bool,
    #[serde(default = "default_true")]
    pub include_git: bool,
    #[serde(default)]
    pub include_config: bool,
    #[serde(default = "default_audit_scan_patterns")]
    pub scan_patterns: String,
    #[serde(default = "default_true")]
    pub external_refs: bool,
    #[serde(default = "default_audit_report_format")]
    pub report_format: String,
    #[serde(default)]
    pub max_output_chars: Option<usize>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct DaemonStartInput {
    pub agent_id: String,
    #[serde(default)]
    pub watch_paths: Vec<String>,
    #[serde(default = "default_daemon_poll_interval_ms")]
    pub poll_interval_ms: u64,
}

fn default_daemon_poll_interval_ms() -> u64 {
    500
}

#[derive(Clone, Debug, Deserialize)]
pub struct DaemonStopInput {
    pub agent_id: String,
}

#[derive(Clone, Debug, Deserialize)]
pub struct DaemonStatusInput {
    pub agent_id: String,
}

#[derive(Clone, Debug, Deserialize)]
pub struct DaemonTickInput {
    pub agent_id: String,
    #[serde(default = "default_daemon_tick_limit")]
    pub max_files: usize,
}

fn default_daemon_tick_limit() -> usize {
    32
}

#[derive(Clone, Debug, Deserialize)]
pub struct AlertsListInput {
    pub agent_id: String,
    #[serde(default)]
    pub include_acked: bool,
    #[serde(default = "default_alert_limit")]
    pub limit: usize,
}

fn default_alert_limit() -> usize {
    50
}

#[derive(Clone, Debug, Deserialize)]
pub struct AlertsAckInput {
    pub agent_id: String,
    pub alert_ids: Vec<String>,
}

fn default_audit_profile() -> String {
    "auto".to_string()
}

fn default_audit_depth() -> String {
    "full".to_string()
}

fn default_audit_scan_patterns() -> String {
    "all".to_string()
}

fn default_audit_report_format() -> String {
    "markdown".to_string()
}

// =========================================================================
// v0.4.0: m1nd.panoramic — Module Risk Overview
// =========================================================================

/// Input for m1nd.panoramic — full module risk panorama.
#[derive(Clone, Debug, Deserialize)]
pub struct PanoramicInput {
    pub agent_id: String,
    /// Namespace prefix to limit scope. None = entire graph.
    #[serde(default)]
    pub scope: Option<String>,
    /// Maximum modules to return. Default: 50.
    #[serde(default = "default_panoramic_top")]
    pub top_n: u32,
}

fn default_panoramic_top() -> u32 {
    50
}

/// A single module entry in the panoramic view.
#[derive(Clone, Debug, Serialize)]
pub struct PanoramicModule {
    pub node_id: String,
    pub label: String,
    pub file_path: String,
    /// Blast radius forward (outbound reachable nodes).
    pub blast_forward: u32,
    /// Blast radius backward (inbound callers).
    pub blast_backward: u32,
    /// PageRank centrality [0.0, 1.0].
    pub centrality: f32,
    /// Combined risk score [0.0, 1.0] — weighted: blast*0.5 + centrality*0.3 + churn*0.2.
    pub combined_risk: f32,
    /// Whether this module is flagged as critical (combined_risk >= 0.7).
    pub is_critical: bool,
}

/// An alert for high-risk modules.
#[derive(Clone, Debug, Serialize)]
pub struct PanoramicAlert {
    pub node_id: String,
    pub label: String,
    pub combined_risk: f32,
    pub reason: String,
}

/// Output for m1nd.panoramic.
#[derive(Clone, Debug, Serialize)]
pub struct PanoramicOutput {
    pub modules: Vec<PanoramicModule>,
    pub total_modules: usize,
    pub critical_alerts: Vec<PanoramicAlert>,
    pub scope_applied: bool,
    pub elapsed_ms: f64,
}

// =========================================================================
// v0.4.0: m1nd.savings — Token Economy Report
// =========================================================================

/// Input for m1nd.savings — token savings and economy summary.
#[derive(Clone, Debug, Deserialize)]
pub struct SavingsInput {
    pub agent_id: String,
}

/// Per-session savings record.
#[derive(Clone, Debug, Serialize)]
pub struct SavingsSessionRecord {
    pub agent_id: String,
    pub session_start_ms: u64,
    pub queries: u32,
    pub tokens_saved: u64,
    pub co2_grams: f64,
}

/// Output for m1nd.savings — cumulative token economy stats.
#[derive(Clone, Debug, Serialize)]
pub struct SavingsOutput {
    /// Tokens saved this session.
    pub session_tokens_saved: u64,
    /// Tokens saved globally (all agents, all sessions).
    pub global_tokens_saved: u64,
    /// CO2 grams saved globally.
    pub global_co2_grams: f64,
    /// Cost saved in USD (based on $0.003/1K tokens saved).
    pub cost_saved_usd: f64,
    /// Recent sessions (last 5).
    pub recent_sessions: Vec<SavingsSessionRecord>,
    /// Formatted display string.
    pub formatted_summary: String,
}

// =========================================================================
// Tests
// =========================================================================

// =========================================================================
// v0.7.0: m1nd.metrics — Structural Codebase Metrics
// =========================================================================

/// Input for m1nd.metrics — per-node structural metrics (LOC, children, degree).
#[derive(Clone, Debug, Deserialize)]
pub struct MetricsInput {
    pub agent_id: String,
    /// File path prefix to limit scope. None = entire graph.
    #[serde(default)]
    pub scope: Option<String>,
    /// Filter by node type: "file", "function", "class", "struct", "module".
    /// Default: ["file"] — metrics per file.
    #[serde(default = "default_metrics_node_types")]
    pub node_types: Vec<String>,
    /// Maximum results to return. Default: 50.
    #[serde(default = "default_metrics_top_k")]
    pub top_k: usize,
    /// Sort order: "loc_desc", "complexity_desc", "name_asc". Default: "loc_desc".
    #[serde(default = "default_metrics_sort")]
    pub sort: String,
}

fn default_metrics_node_types() -> Vec<String> {
    vec!["file".to_string()]
}
fn default_metrics_top_k() -> usize {
    50
}
fn default_metrics_sort() -> String {
    "loc_desc".to_string()
}

/// Output for m1nd.metrics.
#[derive(Clone, Debug, Serialize)]
pub struct MetricsOutput {
    pub entries: Vec<MetricsEntry>,
    pub summary: MetricsSummary,
    pub elapsed_ms: f64,
}

/// Per-node metric entry.
#[derive(Clone, Debug, Serialize)]
pub struct MetricsEntry {
    pub node_id: String,
    pub label: String,
    #[serde(rename = "type")]
    pub node_type: String,
    /// Lines of code (from provenance line_end - line_start + 1, or child span).
    pub loc: u32,
    /// Number of child function nodes.
    pub function_count: u32,
    /// Number of child struct nodes.
    pub struct_count: u32,
    /// Number of child enum nodes.
    pub enum_count: u32,
    /// Number of child class nodes.
    pub class_count: u32,
    /// Outgoing edges (dependencies).
    pub out_degree: u32,
    /// Incoming edges (dependants).
    pub in_degree: u32,
    /// PageRank centrality.
    pub pagerank: f32,
    /// Ratio: children / LOC — higher = more modular.
    pub density: f32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_path: Option<String>,
}

/// Aggregate summary across all entries.
#[derive(Clone, Debug, Serialize)]
pub struct MetricsSummary {
    pub total_files: u32,
    pub total_loc: u64,
    pub total_functions: u32,
    pub total_structs: u32,
    pub total_enums: u32,
    pub total_classes: u32,
    pub avg_loc_per_file: f32,
    pub max_loc_file: String,
    pub max_loc: u32,
}

// =========================================================================
// v0.7.0: m1nd.type_trace — Cross-File Type Usage Tracing
// =========================================================================

/// Input for m1nd.type_trace — find all usage sites of a type/struct/enum
/// across the codebase via directed BFS from the type node.
#[derive(Clone, Debug, Deserialize)]
pub struct TypeTraceInput {
    pub agent_id: String,
    /// The type to trace: name or external_id.
    pub target: String,
    /// BFS direction: "forward", "reverse", "both". Default: "forward".
    #[serde(default = "default_type_trace_direction")]
    pub direction: String,
    /// Maximum BFS hops. Default: 4.
    #[serde(default = "default_type_trace_max_hops")]
    pub max_hops: u8,
    /// Maximum results to return. Default: 50.
    #[serde(default = "default_metrics_top_k")]
    pub top_k: usize,
    /// Group results by file. Default: true.
    #[serde(default = "default_true")]
    pub group_by_file: bool,
}

fn default_type_trace_direction() -> String {
    "forward".to_string()
}
fn default_type_trace_max_hops() -> u8 {
    4
}

/// Output for m1nd.type_trace.
#[derive(Clone, Debug, Serialize)]
pub struct TypeTraceOutput {
    pub target: String,
    pub target_label: String,
    pub target_type: String,
    pub direction: String,
    pub max_hops_used: u8,
    pub usages: Vec<TypeTraceUsage>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub by_file: Vec<TypeTraceFileGroup>,
    pub total_usages: usize,
    pub total_files: usize,
    pub elapsed_ms: f64,
}

/// A single usage site.
#[derive(Clone, Debug, Serialize)]
pub struct TypeTraceUsage {
    pub node_id: String,
    pub label: String,
    #[serde(rename = "type")]
    pub node_type: String,
    pub hops: u8,
    pub relation: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line_start: Option<u32>,
}

/// Usage sites grouped by file.
#[derive(Clone, Debug, Serialize)]
pub struct TypeTraceFileGroup {
    pub file: String,
    pub usage_count: usize,
    pub usages: Vec<TypeTraceUsage>,
}

// =========================================================================
// v0.7.0: m1nd.diagram — Graph-to-Mermaid/DOT Export
// =========================================================================

/// Input for m1nd.diagram — generate a diagram from the graph.
#[derive(Clone, Debug, Deserialize)]
pub struct DiagramInput {
    pub agent_id: String,
    #[serde(default)]
    pub center: Option<String>,
    #[serde(default)]
    pub scope: Option<String>,
    #[serde(default = "default_diagram_format")]
    pub format: String,
    #[serde(default = "default_diagram_max_nodes")]
    pub max_nodes: usize,
    #[serde(default = "default_diagram_depth")]
    pub depth: u8,
    #[serde(default)]
    pub node_types: Vec<String>,
    #[serde(default = "default_true")]
    pub show_relations: bool,
    #[serde(default)]
    pub show_pagerank: bool,
    #[serde(default = "default_diagram_direction")]
    pub direction: String,
}

fn default_diagram_format() -> String {
    "mermaid".to_string()
}
fn default_diagram_max_nodes() -> usize {
    30
}
fn default_diagram_depth() -> u8 {
    2
}
fn default_diagram_direction() -> String {
    "TD".to_string()
}

/// Output for m1nd.diagram.
#[derive(Clone, Debug, Serialize)]
pub struct DiagramOutput {
    pub source: String,
    pub format: String,
    pub node_count: usize,
    pub edge_count: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub center_node: Option<String>,
    pub elapsed_ms: f64,
}

// =========================================================================
// Tests
// =========================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // --- L2 ---

    #[test]
    fn seek_input_deserializes_minimal() {
        let json = r#"{"query": "find auth code", "agent_id": "jimi"}"#;
        let input: SeekInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.query, "find auth code");
        assert_eq!(input.agent_id, "jimi");
        assert_eq!(input.top_k, 20);
        assert!(input.scope.is_none());
        assert!(input.node_types.is_empty());
        assert!((input.min_score - 0.1).abs() < f32::EPSILON);
        assert!(input.graph_rerank);
    }

    #[test]
    fn scan_input_defaults() {
        let json = r#"{"pattern": "error_handling", "agent_id": "jimi"}"#;
        let input: ScanInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.pattern, "error_handling");
        assert!((input.severity_min - 0.3).abs() < f32::EPSILON);
        assert!(input.graph_validate);
        assert_eq!(input.limit, 50);
    }

    // --- L3 ---

    #[test]
    fn timeline_input_deserializes_minimal() {
        let json = r#"{"node": "file::backend/config.py", "agent_id": "jimi"}"#;
        let input: TimelineInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.node, "file::backend/config.py");
        assert_eq!(input.depth, "30d");
        assert!(input.include_co_changes);
        assert!(input.include_churn);
        assert_eq!(input.top_k, 10);
    }

    #[test]
    fn diverge_input_with_scope() {
        let json = r#"{
            "agent_id": "jimi",
            "baseline": "2026-03-01",
            "scope": "backend/stormender*"
        }"#;
        let input: DivergeInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.baseline, "2026-03-01");
        assert_eq!(input.scope.as_deref(), Some("backend/stormender*"));
        assert!(input.include_coupling_changes);
        assert!(input.include_anomalies);
    }

    // --- L4 ---

    #[test]
    fn trail_save_input_minimal() {
        let json = r#"{"agent_id": "jimi", "label": "race condition investigation"}"#;
        let input: TrailSaveInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.label, "race condition investigation");
        assert!(input.hypotheses.is_empty());
        assert!(input.conclusions.is_empty());
        assert!(input.open_questions.is_empty());
        assert!(input.tags.is_empty());
    }

    #[test]
    fn trail_resume_input_defaults() {
        let json = r#"{"agent_id": "jimi", "trail_id": "trail_jimi_001_abc"}"#;
        let input: TrailResumeInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.trail_id, "trail_jimi_001_abc");
        assert!(!input.force);
        assert_eq!(input.max_reactivated_nodes, 5);
        assert_eq!(input.max_resume_hints, 4);
    }

    #[test]
    fn trail_merge_input_two_trails() {
        let json = r#"{
            "agent_id": "jimi",
            "trail_ids": ["trail_a", "trail_b"]
        }"#;
        let input: TrailMergeInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.trail_ids.len(), 2);
        assert!(input.label.is_none());
    }

    #[test]
    fn trail_list_input_with_filters() {
        let json = r#"{
            "agent_id": "jimi",
            "filter_status": "saved",
            "filter_tags": ["stormender", "concurrency"]
        }"#;
        let input: TrailListInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.filter_status.as_deref(), Some("saved"));
        assert_eq!(input.filter_tags.len(), 2);
    }

    // --- L5 ---

    #[test]
    fn hypothesize_input_minimal() {
        let json = r#"{
            "claim": "chat_handler never validates session tokens",
            "agent_id": "jimi"
        }"#;
        let input: HypothesizeInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.claim, "chat_handler never validates session tokens");
        assert_eq!(input.max_hops, 5);
        assert!(input.include_ghost_edges);
        assert!(input.include_partial_flow);
        assert_eq!(input.path_budget, 1000);
    }

    #[test]
    fn differential_input_minimal() {
        let json = r#"{
            "agent_id": "jimi",
            "snapshot_a": "before.json",
            "snapshot_b": "current"
        }"#;
        let input: DifferentialInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.snapshot_a, "before.json");
        assert_eq!(input.snapshot_b, "current");
        assert!(input.question.is_none());
        assert!(input.focus_nodes.is_empty());
    }

    // --- L6 ---

    #[test]
    fn trace_input_minimal() {
        let json = r#"{
            "error_text": "Traceback (most recent call last):\n  File \"test.py\", line 1\nTypeError: bad",
            "agent_id": "jimi"
        }"#;
        let input: TraceInput = serde_json::from_str(json).unwrap();
        assert!(input.language.is_none());
        assert!((input.window_hours - 24.0).abs() < f32::EPSILON);
        assert_eq!(input.top_k, 10);
    }

    #[test]
    fn validate_plan_input_with_actions() {
        let json = r#"{
            "agent_id": "jimi",
            "actions": [
                {"action_type": "modify", "file_path": "backend/config.py"},
                {"action_type": "test", "file_path": "backend/tests/test_config.py"}
            ]
        }"#;
        let input: ValidatePlanInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.actions.len(), 2);
        assert!(input.include_test_impact);
        assert!(input.include_risk_score);
        assert_eq!(input.actions[0].action_type, "modify");
        assert!(input.actions[0].depends_on.is_empty());
    }

    // --- L7 ---

    #[test]
    fn federate_input_minimal() {
        let json = r#"{
            "agent_id": "jimi",
            "repos": [
                {"name": "my-project", "path": "/tmp/my-project"},
                {"name": "my-library", "path": "/tmp/my-library"}
            ]
        }"#;
        let input: FederateInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.repos.len(), 2);
        assert!(input.detect_cross_repo_edges);
        assert!(!input.incremental);
        assert_eq!(input.repos[0].name, "my-project");
        assert_eq!(input.repos[1].adapter, "code");
    }

    // --- TEMPESTA: surgical_context + apply schema parity ---

    #[test]
    fn surgical_context_input_minimal() {
        let json = r#"{"node_id": "file::backend/chat_handler.py", "agent_id": "jimi"}"#;
        let input: SurgicalContextInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.node_id, "file::backend/chat_handler.py");
        assert_eq!(input.agent_id, "jimi");
        assert_eq!(input.max_lines, 200);
        assert!(input.include_callers);
        assert!(input.include_callees);
        assert!(input.include_blast_radius);
        assert!(input.include_trust_score);
        assert_eq!(input.max_deps, 20);
    }

    #[test]
    fn surgical_context_input_custom_max_lines() {
        let json = r#"{
            "node_id": "func::handle_chat",
            "agent_id": "forge",
            "max_lines": 50,
            "include_callers": false,
            "max_deps": 5
        }"#;
        let input: SurgicalContextInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.max_lines, 50);
        assert!(!input.include_callers);
        assert!(input.include_callees);
        assert_eq!(input.max_deps, 5);
    }

    #[test]
    fn apply_input_minimal() {
        let json = r#"{
            "node_id": "func::handle_chat",
            "agent_id": "forge",
            "file_path": "/tmp/project/backend/chat_handler.py",
            "line_start": 42,
            "line_end": 55,
            "new_content": "def handle_chat(request):\n    return Response(200)\n"
        }"#;
        let input: ApplyInput = serde_json::from_str(json).unwrap();
        assert_eq!(input.node_id, "func::handle_chat");
        assert_eq!(input.line_start, 42);
        assert_eq!(input.line_end, 55);
        assert!(input.fail_on_stale);
        assert!(input.include_predictions);
        assert_eq!(input.predict_top_k, 5);
    }

    #[test]
    fn apply_input_no_predictions() {
        let json = r#"{
            "node_id": "func::process_task",
            "agent_id": "forge",
            "file_path": "/tmp/project/backend/worker_pool.py",
            "line_start": 10,
            "line_end": 10,
            "new_content": "    pass\n",
            "include_predictions": false
        }"#;
        let input: ApplyInput = serde_json::from_str(json).unwrap();
        assert!(!input.include_predictions);
        assert!(input.fail_on_stale); // default still true
    }
}