eidetic-engine 0.15.1

Durable, local-first, explainable memory for coding 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
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
//! Preflight risk assessment operations (EE-391).
//!
//! Assess task-specific risks before work starts so memory changes
//! agent behavior at the moment of risk rather than only after a mistake.
//!
//! # Operations
//!
//! - **run**: Execute a preflight risk assessment for a task
//! - **show**: Display details of a preflight run
//! - **close**: Mark a preflight run as completed

use std::collections::BTreeMap;
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::time::Instant;

use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};

use crate::core::feedback::{
    PreflightFeedbackKind, RecordFeedbackReport, RecordOutcomeOptions, TaskOutcome,
    infer_preflight_feedback_kind, record_preflight_outcome,
};
use crate::core::preflight_guard::matches_drop_table_sql;
use crate::models::DomainError;
use crate::models::claims::{ClaimEntry, ClaimStatus};
use crate::models::episode::{RegretCategory, RegretEntry as LedgerRegretEntry};
use crate::models::preflight::{
    PREFLIGHT_RUN_ID_PREFIX, PreflightRun, PreflightStatus, RISK_BRIEF_ID_PREFIX, RiskBrief,
    RiskCategory, RiskItem, RiskLevel, TRIPWIRE_ID_PREFIX, Tripwire, TripwireAction, TripwireType,
};

/// Schema for preflight reports.
pub const PREFLIGHT_REPORT_SCHEMA_V1: &str = "ee.preflight.report.v1";

/// Schema for the read-only agent operating contract extracted from repo docs.
pub const AGENT_OPERATING_CONTRACT_SCHEMA_V1: &str = "ee.agent_operating_contract.v1";

/// Schema for the lightweight project-local preflight run store.
pub const PREFLIGHT_RUN_STORE_SCHEMA_V1: &str = "ee.preflight_run_store.v1";

/// Location of persisted preflight runs, relative to the workspace root.
pub const PREFLIGHT_RUN_STORE_RELATIVE_PATH: &str = ".ee/preflight_runs.json";

/// Maximum size for `<workspace>/.ee/preflight_runs.json`.
///
/// `read_preflight_run_store` is called from `ee preflight run`,
/// `ee preflight show`, `ee preflight close`, and the
/// generate-tripwires-from-sources persistence path (see
/// `persist_preflight_run` at this file:1009). Each call calls
/// `fs::read_to_string` on the store path with no size bound. A workspace
/// file accidentally inflated past memory limits (`cat /dev/urandom > .ee/preflight_runs.json`)
/// or maliciously planted by a peer agent would OOM the CLI on every
/// preflight surface. Parallel defense to `PREFLIGHT_RULES_MAX_BYTES` in
/// `src/core/preflight_guard.rs` and `HANDOFF_FILE_MAX_BYTES` in
/// `src/core/handoff.rs`.
///
/// Realistic preflight run stores are O(1KB) per run × maybe a few hundred
/// runs retained = O(100KB). 4 MiB is a very generous ceiling that still
/// bounds the worst-case allocation to a single short-lived buffer.
pub const PREFLIGHT_RUN_STORE_MAX_BYTES: u64 = 4 * 1024 * 1024;

/// Default minimum score for turning evidence into a tripwire.
pub const DEFAULT_TRIPWIRE_SOURCE_SCORE: f64 = 0.5;

/// Default maximum number of generated tripwires per run.
pub const DEFAULT_MAX_GENERATED_TRIPWIRES: usize = 8;

/// Default age after which persisted preflight evidence must be refreshed.
pub const DEFAULT_STALE_EVIDENCE_DAYS: i64 = 14;

const TRAUMA_GUARD_PREFLIGHT_SURFACE: &str = "trauma_guard_preflight";

fn elapsed_ms_since(started: Instant) -> u64 {
    u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)
}

fn preflight_trace_workspace_id(workspace: &Path) -> String {
    let path = workspace.to_string_lossy();
    let digest = blake3::hash(path.as_bytes()).to_hex().to_string();
    format!("wsp_{}", &digest[..16])
}

fn trace_trauma_guard_preflight(
    workspace: &Path,
    phase: &'static str,
    elapsed_ms: u64,
    degraded_codes: &[&str],
) {
    tracing::info!(
        workspace_id = %preflight_trace_workspace_id(workspace),
        request_id = "preflight_run_request",
        bead_id = option_env!("EE_TRACE_BEAD_ID").unwrap_or("bd-3usjw.6"),
        surface = TRAUMA_GUARD_PREFLIGHT_SURFACE,
        phase,
        elapsed_ms,
        degraded_codes = ?degraded_codes,
        "trauma guard preflight risk checkpoint"
    );
}

/// Configuration for deterministic tripwire generation.
#[derive(Clone, Debug, PartialEq)]
pub struct TripwireGenerationConfig {
    /// Minimum normalized source score required for generation.
    pub min_source_score: f64,
    /// Maximum tripwires generated for a preflight run.
    pub max_tripwires: usize,
}

impl Default for TripwireGenerationConfig {
    fn default() -> Self {
        Self {
            min_source_score: DEFAULT_TRIPWIRE_SOURCE_SCORE,
            max_tripwires: DEFAULT_MAX_GENERATED_TRIPWIRES,
        }
    }
}

/// Evidence surface that can seed a preflight tripwire.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TripwireSourceKind {
    /// A high-utility memory already known to prevent mistakes.
    HighUtilityMemory,
    /// A regret ledger entry from counterfactual analysis.
    RegretLedgerEntry,
    /// An executable claim or claim manifest surface.
    Claim,
    /// A dependency contract or forbidden dependency gate.
    DependencyContract,
    /// A counterfactual candidate that has not yet become regret.
    CounterfactualCandidate,
}

impl TripwireSourceKind {
    /// Stable string representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::HighUtilityMemory => "high_utility_memory",
            Self::RegretLedgerEntry => "regret_ledger_entry",
            Self::Claim => "claim",
            Self::DependencyContract => "dependency_contract",
            Self::CounterfactualCandidate => "counterfactual_candidate",
        }
    }

    const fn rank(self) -> u8 {
        match self {
            Self::RegretLedgerEntry => 0,
            Self::DependencyContract => 1,
            Self::HighUtilityMemory => 2,
            Self::CounterfactualCandidate => 3,
            Self::Claim => 4,
        }
    }
}

/// A normalized source candidate for tripwire generation.
#[derive(Clone, Debug, PartialEq)]
pub struct TripwireSource {
    /// Source surface kind.
    pub kind: TripwireSourceKind,
    /// Stable source identifier.
    pub source_id: String,
    /// Human-readable evidence summary.
    pub summary: String,
    /// Normalized utility/regret/confidence score.
    pub score: f64,
    /// Risk category this source guards.
    pub risk_category: RiskCategory,
    /// Risk level this source implies.
    pub risk_level: RiskLevel,
    /// Lowercase task terms that make this source task-relevant.
    pub trigger_terms: Vec<String>,
    /// Action to take if the tripwire fires.
    pub action: TripwireAction,
    /// Tripwire type to create.
    pub tripwire_type: TripwireType,
}

impl TripwireSource {
    /// Build a source from a high-utility memory.
    #[must_use]
    pub fn high_utility_memory(
        memory_id: impl Into<String>,
        summary: impl Into<String>,
        utility: f64,
        trigger_terms: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        let score = normalized_score(utility);
        Self {
            kind: TripwireSourceKind::HighUtilityMemory,
            source_id: memory_id.into(),
            summary: summary.into(),
            score,
            risk_category: RiskCategory::Other,
            risk_level: if score >= 0.85 {
                RiskLevel::High
            } else {
                RiskLevel::Medium
            },
            trigger_terms: normalize_terms(trigger_terms),
            action: TripwireAction::Warn,
            tripwire_type: TripwireType::Custom,
        }
    }

    /// Build a source from a regret ledger entry.
    #[must_use]
    pub fn regret_entry(
        entry: &LedgerRegretEntry,
        summary: impl Into<String>,
        trigger_terms: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        let score = normalized_score(entry.regret_score * entry.confidence);
        let (risk_category, risk_level, action) = regret_profile(entry.category, score);
        Self {
            kind: TripwireSourceKind::RegretLedgerEntry,
            source_id: entry.id.clone(),
            summary: summary.into(),
            score,
            risk_category,
            risk_level,
            trigger_terms: normalize_terms(trigger_terms),
            action,
            tripwire_type: TripwireType::ErrorThreshold,
        }
    }

    /// Build a source from an executable claim.
    #[must_use]
    pub fn claim_entry(
        claim: &ClaimEntry,
        score: f64,
        trigger_terms: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        let score = normalized_score(score);
        let (risk_level, action) = claim_profile(claim.status, score);
        Self {
            kind: TripwireSourceKind::Claim,
            source_id: claim.id.to_string(),
            summary: claim.title.clone(),
            score,
            risk_category: RiskCategory::Compliance,
            risk_level,
            trigger_terms: normalize_terms(trigger_terms),
            action,
            tripwire_type: TripwireType::Custom,
        }
    }

    /// Build a source from a dependency contract.
    #[must_use]
    pub fn dependency_contract(
        contract_id: impl Into<String>,
        summary: impl Into<String>,
        critical: bool,
        trigger_terms: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            kind: TripwireSourceKind::DependencyContract,
            source_id: contract_id.into(),
            summary: summary.into(),
            score: if critical { 1.0 } else { 0.7 },
            risk_category: RiskCategory::Compliance,
            risk_level: if critical {
                RiskLevel::Critical
            } else {
                RiskLevel::High
            },
            trigger_terms: normalize_terms(trigger_terms),
            action: if critical {
                TripwireAction::Halt
            } else {
                TripwireAction::Pause
            },
            tripwire_type: TripwireType::FileChange,
        }
    }

    /// Build a source from a counterfactual candidate.
    #[must_use]
    pub fn counterfactual_candidate(
        candidate_id: impl Into<String>,
        hypothesis: impl Into<String>,
        confidence: f64,
        trigger_terms: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        let score = normalized_score(confidence);
        Self {
            kind: TripwireSourceKind::CounterfactualCandidate,
            source_id: candidate_id.into(),
            summary: hypothesis.into(),
            score,
            risk_category: RiskCategory::Stability,
            risk_level: if score >= 0.75 {
                RiskLevel::High
            } else {
                RiskLevel::Medium
            },
            trigger_terms: normalize_terms(trigger_terms),
            action: if score >= 0.75 {
                TripwireAction::Pause
            } else {
                TripwireAction::Warn
            },
            tripwire_type: TripwireType::Custom,
        }
    }

    fn matches_task(&self, task_input: &str) -> bool {
        self.trigger_terms.is_empty()
            || self
                .trigger_terms
                .iter()
                .any(|term| task_input.contains(term.as_str()))
    }
}

/// A generated tripwire with source provenance.
#[derive(Clone, Debug, PartialEq)]
pub struct GeneratedTripwire {
    /// Generated tripwire domain object.
    pub tripwire: Tripwire,
    /// Evidence source kind.
    pub source_kind: TripwireSourceKind,
    /// Evidence source ID.
    pub source_id: String,
    /// Score used for ranking and thresholding.
    pub source_score: f64,
    /// Trigger terms copied from the evidence source.
    pub trigger_terms: Vec<String>,
    /// Human-readable provenance facts for the generated tripwire.
    pub provenance: Vec<String>,
    /// Risk level used for deterministic ordering.
    pub risk_level: RiskLevel,
}

/// Options for running a preflight assessment.
#[derive(Clone, Debug)]
pub struct RunOptions {
    /// Workspace path.
    pub workspace: PathBuf,
    /// Task input/prompt to assess.
    pub task_input: String,
    /// Check for similar past failures.
    pub check_history: bool,
    /// Check for related tripwires.
    pub check_tripwires: bool,
    /// Maximum risk level to auto-clear.
    pub auto_clear_threshold: Option<RiskLevel>,
    /// Whether to run in dry-run mode.
    pub dry_run: bool,
    /// Persist the completed run into the workspace-local preflight run store.
    pub persist_run: bool,
    /// Evidence sources available for deterministic tripwire generation.
    pub tripwire_sources: Vec<TripwireSource>,
    /// Tripwire generation thresholds.
    pub tripwire_generation: TripwireGenerationConfig,
}

impl Default for RunOptions {
    fn default() -> Self {
        Self {
            workspace: PathBuf::from("."),
            task_input: String::new(),
            check_history: true,
            check_tripwires: true,
            auto_clear_threshold: Some(RiskLevel::Medium),
            dry_run: false,
            persist_run: false,
            tripwire_sources: Vec::new(),
            tripwire_generation: TripwireGenerationConfig::default(),
        }
    }
}

/// Options for showing a preflight run.
#[derive(Clone, Debug)]
pub struct ShowOptions {
    /// Workspace path.
    pub workspace: PathBuf,
    /// Preflight run ID to show.
    pub run_id: String,
    /// Include risk brief details.
    pub include_brief: bool,
    /// Include tripwire details.
    pub include_tripwires: bool,
}

impl Default for ShowOptions {
    fn default() -> Self {
        Self {
            workspace: PathBuf::from("."),
            run_id: String::new(),
            include_brief: true,
            include_tripwires: true,
        }
    }
}

/// Options for closing a preflight run.
#[derive(Clone, Debug)]
pub struct CloseOptions {
    /// Workspace path.
    pub workspace: PathBuf,
    /// Preflight run ID to close.
    pub run_id: String,
    /// Close as cleared for execution.
    pub cleared: bool,
    /// Reason for closing (especially if blocked).
    pub reason: Option<String>,
    /// Observed task outcome to feed into future scoring.
    pub task_outcome: Option<TaskOutcome>,
    /// Explicit feedback class for the warning, if known.
    pub feedback_kind: Option<PreflightFeedbackKind>,
    /// Whether to run in dry-run mode.
    pub dry_run: bool,
}

impl Default for CloseOptions {
    fn default() -> Self {
        Self {
            workspace: PathBuf::from("."),
            run_id: String::new(),
            cleared: false,
            reason: None,
            task_outcome: None,
            feedback_kind: None,
            dry_run: false,
        }
    }
}

/// Report from running a preflight assessment.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RunReport {
    pub schema: String,
    pub run_id: String,
    pub task_input: String,
    pub status: String,
    pub risk_level: String,
    pub cleared: bool,
    pub block_reason: Option<String>,
    pub risk_brief_id: Option<String>,
    pub top_risks: Vec<String>,
    pub ask_now_prompts: Vec<String>,
    pub must_verify_checks: Vec<String>,
    pub evidence_ids: Vec<String>,
    pub next_action: String,
    pub risks_identified: usize,
    pub tripwires_set: usize,
    pub tripwires: Vec<TripwireView>,
    pub degraded: Vec<PreflightDegradation>,
    pub dry_run: bool,
    pub started_at: String,
    pub completed_at: Option<String>,
}

impl RunReport {
    #[must_use]
    pub fn new(run_id: String, task_input: String) -> Self {
        Self {
            schema: PREFLIGHT_REPORT_SCHEMA_V1.to_owned(),
            run_id,
            task_input,
            status: PreflightStatus::Running.as_str().to_owned(),
            risk_level: RiskLevel::Unknown.as_str().to_owned(),
            cleared: false,
            block_reason: None,
            risk_brief_id: None,
            top_risks: Vec::new(),
            ask_now_prompts: Vec::new(),
            must_verify_checks: Vec::new(),
            evidence_ids: Vec::new(),
            next_action: "assess_risk".to_owned(),
            risks_identified: 0,
            tripwires_set: 0,
            tripwires: Vec::new(),
            degraded: Vec::new(),
            dry_run: false,
            started_at: Utc::now().to_rfc3339(),
            completed_at: None,
        }
    }

    #[must_use]
    pub fn to_json(&self) -> String {
        crate::core::serialize_or_error(self)
    }
}

/// Report from showing a preflight run.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ShowReport {
    pub schema: String,
    pub run: PreflightRunView,
    pub brief: Option<RiskBriefView>,
    pub tripwires: Vec<TripwireView>,
    pub degraded: Vec<PreflightDegradation>,
}

impl ShowReport {
    #[must_use]
    pub fn new(run: PreflightRunView) -> Self {
        Self {
            schema: PREFLIGHT_REPORT_SCHEMA_V1.to_owned(),
            run,
            brief: None,
            tripwires: Vec::new(),
            degraded: Vec::new(),
        }
    }

    #[must_use]
    pub fn to_json(&self) -> String {
        crate::core::serialize_or_error(self)
    }
}

/// View of a preflight run for display.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PreflightRunView {
    pub id: String,
    pub task_input: String,
    pub status: String,
    pub risk_level: String,
    pub cleared: bool,
    pub block_reason: Option<String>,
    pub started_at: String,
    pub completed_at: Option<String>,
    pub duration_ms: Option<u64>,
}

impl From<&PreflightRun> for PreflightRunView {
    fn from(run: &PreflightRun) -> Self {
        Self {
            id: run.id.clone(),
            task_input: run.task_input.clone(),
            status: run.status.as_str().to_owned(),
            risk_level: run.risk_level.as_str().to_owned(),
            cleared: run.cleared,
            block_reason: run.block_reason.clone(),
            started_at: run.started_at.clone(),
            completed_at: run.completed_at.clone(),
            duration_ms: run.duration_ms,
        }
    }
}

/// View of a risk brief for display.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RiskBriefView {
    pub id: String,
    pub risk_level: String,
    pub summary: Option<String>,
    pub risks: Vec<RiskItemView>,
    pub recommendations: Vec<String>,
}

impl From<&RiskBrief> for RiskBriefView {
    fn from(brief: &RiskBrief) -> Self {
        Self {
            id: brief.id.clone(),
            risk_level: brief.risk_level.as_str().to_owned(),
            summary: brief.summary.clone(),
            risks: brief.risks.iter().map(RiskItemView::from).collect(),
            recommendations: brief.recommendations.clone(),
        }
    }
}

/// View of a risk item for display.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RiskItemView {
    pub category: String,
    pub level: String,
    pub description: String,
    pub mitigation: Option<String>,
}

impl From<&RiskItem> for RiskItemView {
    fn from(item: &RiskItem) -> Self {
        Self {
            category: item.category.as_str().to_owned(),
            level: item.level.as_str().to_owned(),
            description: item.description.clone(),
            mitigation: item.mitigation.clone(),
        }
    }
}

/// View of a tripwire for display.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TripwireView {
    pub id: String,
    pub name: String,
    pub status: String,
    pub tripwire_type: String,
    pub action: String,
    pub condition: String,
    pub message: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_score: Option<f64>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub trigger_terms: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub provenance: Vec<String>,
}

impl From<&Tripwire> for TripwireView {
    fn from(tripwire: &Tripwire) -> Self {
        Self {
            id: tripwire.id.clone(),
            name: tripwire
                .message
                .clone()
                .unwrap_or_else(|| tripwire.tripwire_type.as_str().to_owned()),
            status: tripwire.state.as_str().to_owned(),
            tripwire_type: tripwire.tripwire_type.as_str().to_owned(),
            action: tripwire.action.as_str().to_owned(),
            condition: tripwire.condition.clone(),
            message: tripwire.message.clone(),
            source_kind: None,
            source_id: None,
            source_score: None,
            trigger_terms: Vec::new(),
            provenance: Vec::new(),
        }
    }
}

impl From<&GeneratedTripwire> for TripwireView {
    fn from(generated: &GeneratedTripwire) -> Self {
        let mut view = Self::from(&generated.tripwire);
        view.source_kind = Some(generated.source_kind.as_str().to_owned());
        view.source_id = Some(generated.source_id.clone());
        view.source_score = Some(generated.source_score);
        view.trigger_terms = generated.trigger_terms.clone();
        view.provenance = generated.provenance.clone();
        view
    }
}

/// Report from closing a preflight run.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CloseReport {
    pub schema: String,
    pub run_id: String,
    pub previous_status: String,
    pub new_status: String,
    pub cleared: bool,
    pub reason: Option<String>,
    pub task_outcome: Option<String>,
    pub feedback: Option<RecordFeedbackReport>,
    pub dry_run: bool,
    pub closed_at: String,
}

impl CloseReport {
    #[must_use]
    pub fn new(run_id: String, previous_status: PreflightStatus) -> Self {
        Self {
            schema: PREFLIGHT_REPORT_SCHEMA_V1.to_owned(),
            run_id,
            previous_status: previous_status.as_str().to_owned(),
            new_status: PreflightStatus::Completed.as_str().to_owned(),
            cleared: false,
            reason: None,
            task_outcome: None,
            feedback: None,
            dry_run: false,
            closed_at: Utc::now().to_rfc3339(),
        }
    }

    #[must_use]
    pub fn to_json(&self) -> String {
        crate::core::serialize_or_error(self)
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
struct PreflightRunStoreDocument {
    schema: String,
    runs: Vec<StoredPreflightRun>,
}

impl Default for PreflightRunStoreDocument {
    fn default() -> Self {
        Self {
            schema: PREFLIGHT_RUN_STORE_SCHEMA_V1.to_owned(),
            runs: Vec::new(),
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
struct StoredPreflightRun {
    report: RunReport,
    close_report: Option<CloseReport>,
}

/// Honest degraded-mode marker for preflight readiness contracts.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PreflightDegradation {
    pub code: String,
    pub severity: String,
    pub message: String,
    pub repair: Option<String>,
}

impl PreflightDegradation {
    #[must_use]
    pub fn evidence_unavailable(message: impl Into<String>) -> Self {
        Self {
            code: "preflight_evidence_unavailable".to_owned(),
            severity: "medium".to_owned(),
            message: message.into(),
            repair: Some("Provide explicit preflight evidence sources or run a project-local preflight risk-review skill.".to_owned()),
        }
    }

    #[must_use]
    pub fn evidence_stale(message: impl Into<String>) -> Self {
        Self {
            code: "preflight_evidence_stale".to_owned(),
            severity: "warning".to_owned(),
            message: message.into(),
            repair: Some("ee preflight run --help".to_owned()),
        }
    }
}

fn generate_id() -> String {
    uuid::Uuid::now_v7().to_string()
}

/// Path for the workspace-local persisted preflight run store.
#[must_use]
pub fn preflight_run_store_path(workspace: &Path) -> PathBuf {
    workspace.join(PREFLIGHT_RUN_STORE_RELATIVE_PATH)
}

fn read_preflight_run_store(store_path: &Path) -> Result<PreflightRunStoreDocument, DomainError> {
    ensure_no_symlink_components(store_path, "read")?;
    match fs::symlink_metadata(store_path) {
        Ok(metadata) if metadata.file_type().is_file() => {
            // Size cap before the unbounded `read_to_string` below.
            // Realistic preflight run stores are O(100KB) total; an
            // inflated file (`cat /dev/urandom >> .ee/preflight_runs.json`
            // or a stuck-loop writer) would otherwise pin a multi-GB
            // allocation on every `ee preflight {run,show,close}` call.
            // Reject early with a structured storage error and a repair
            // hint so the operator knows what to truncate.
            if metadata.len() > PREFLIGHT_RUN_STORE_MAX_BYTES {
                return Err(DomainError::Storage {
                    message: format!(
                        "Refusing to read preflight run store `{}`: {} bytes exceeds the {} byte ceiling.",
                        store_path.display(),
                        metadata.len(),
                        PREFLIGHT_RUN_STORE_MAX_BYTES
                    ),
                    repair: Some(format!(
                        "Truncate or rewrite {} (typical stores are <100KB).",
                        store_path.display()
                    )),
                });
            }
        }
        Ok(_) => {
            return Err(DomainError::Storage {
                message: format!(
                    "Refusing to read preflight run store `{}` because it is not a regular file.",
                    store_path.display()
                ),
                repair: Some(
                    "Replace the preflight run store with a regular JSON file.".to_owned(),
                ),
            });
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Ok(PreflightRunStoreDocument::default());
        }
        Err(error) => {
            return Err(DomainError::Storage {
                message: format!(
                    "Failed to stat preflight run store `{}`: {error}",
                    store_path.display()
                ),
                repair: Some("Check workspace .ee permissions.".to_owned()),
            });
        }
    }

    let text = read_preflight_run_store_file_no_follow(store_path).map_err(|error| {
        DomainError::Storage {
            message: format!(
                "Failed to read preflight run store `{}`: {error}",
                store_path.display()
            ),
            repair: Some("Check workspace .ee permissions.".to_owned()),
        }
    })?;

    let document: PreflightRunStoreDocument =
        serde_json::from_str(&text).map_err(|error| DomainError::Storage {
            message: format!(
                "Failed to parse preflight run store `{}`: {error}",
                store_path.display()
            ),
            repair: Some("Repair or remove the malformed preflight run store.".to_owned()),
        })?;

    if document.schema == PREFLIGHT_RUN_STORE_SCHEMA_V1 {
        Ok(document)
    } else {
        Err(DomainError::Storage {
            message: format!(
                "Unsupported preflight run store schema `{}` in `{}`.",
                document.schema,
                store_path.display()
            ),
            repair: Some(format!(
                "Expected schema `{PREFLIGHT_RUN_STORE_SCHEMA_V1}`; migrate or rebuild the store."
            )),
        })
    }
}

fn read_preflight_run_store_file_no_follow(store_path: &Path) -> Result<String, std::io::Error> {
    // Bounded read with `take(CAP + 1)`. The caller already rejects an
    // oversized file via the `fs::symlink_metadata().len() > CAP` check
    // above, but that stat-then-read shape is TOCTOU-racy: a peer
    // process can grow the file between the stat and the open so the
    // underlying `read_to_string` would still allocate past CAP. The
    // bounded read closes the window — if the file has grown to
    // CAP + 1 bytes by the time we hit it, we bail with InvalidData
    // and the caller wraps that into a structured Storage error. The
    // metadata pre-check is kept as a cheap fast-path rejection that
    // also surfaces a friendlier repair hint for the common non-racy
    // case.
    let file = open_preflight_run_store_file_for_read(store_path)?;
    let limit = PREFLIGHT_RUN_STORE_MAX_BYTES.saturating_add(1);
    let mut bytes = Vec::new();
    file.take(limit).read_to_end(&mut bytes)?;
    if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > PREFLIGHT_RUN_STORE_MAX_BYTES {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!(
                "preflight run store at {} grew past the {PREFLIGHT_RUN_STORE_MAX_BYTES}-byte cap after the metadata check (TOCTOU)",
                store_path.display()
            ),
        ));
    }
    String::from_utf8(bytes)
        .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
}

fn open_preflight_run_store_file_for_read(store_path: &Path) -> Result<fs::File, std::io::Error> {
    let mut options = fs::OpenOptions::new();
    options.read(true);
    configure_preflight_run_store_open_no_follow(&mut options);
    options.open(store_path)
}

#[cfg(all(unix, not(any(target_os = "espidf", target_os = "horizon"))))]
fn configure_preflight_run_store_open_no_follow(options: &mut fs::OpenOptions) {
    use std::os::unix::fs::OpenOptionsExt;

    options.custom_flags(rustix::fs::OFlags::NOFOLLOW.bits() as i32);
}

#[cfg(not(all(unix, not(any(target_os = "espidf", target_os = "horizon")))))]
fn configure_preflight_run_store_open_no_follow(_options: &mut fs::OpenOptions) {}

fn write_preflight_run_store(
    store_path: &Path,
    store: &mut PreflightRunStoreDocument,
) -> Result<(), DomainError> {
    ensure_no_symlink_components(store_path, "write")?;
    if let Some(parent) = store_path.parent() {
        fs::create_dir_all(parent).map_err(|error| DomainError::Storage {
            message: format!(
                "Failed to create preflight run store directory `{}`: {error}",
                parent.display()
            ),
            repair: Some("Check workspace .ee permissions.".to_owned()),
        })?;
    }
    ensure_no_symlink_components(store_path, "write")?;
    ensure_preflight_run_store_final_path_for_write(store_path)?;

    store.runs.sort_by(|left, right| {
        left.report
            .started_at
            .cmp(&right.report.started_at)
            .then_with(|| left.report.run_id.cmp(&right.report.run_id))
    });

    let text = serde_json::to_string_pretty(store).map_err(|error| DomainError::Storage {
        message: format!("Failed to serialize preflight run store: {error}"),
        repair: Some("Report the invalid preflight run payload.".to_owned()),
    })?;

    let temp_path = store_path.with_extension("json.tmp");
    ensure_no_symlink_components(&temp_path, "write")?;
    ensure_preflight_run_store_temp_path_for_write(&temp_path)?;
    write_preflight_run_store_temp_file(&temp_path, &format!("{text}\n"))?;
    publish_preflight_run_store_temp_file(&temp_path, store_path)
}

fn publish_preflight_run_store_temp_file(
    temp_path: &Path,
    store_path: &Path,
) -> Result<(), DomainError> {
    ensure_no_symlink_components(temp_path, "publish")?;
    ensure_preflight_run_store_temp_path_is_regular(temp_path)?;
    ensure_no_symlink_components(store_path, "publish")?;
    ensure_preflight_run_store_final_path_for_write(store_path)?;
    fs::rename(temp_path, store_path).map_err(|error| DomainError::Storage {
        message: format!(
            "Failed to publish preflight run store `{}` from temp file `{}`: {error}",
            store_path.display(),
            temp_path.display()
        ),
        repair: Some("Check workspace .ee permissions.".to_owned()),
    })
}

fn ensure_preflight_run_store_temp_path_is_regular(temp_path: &Path) -> Result<(), DomainError> {
    match fs::symlink_metadata(temp_path) {
        Ok(metadata) if metadata.file_type().is_file() => Ok(()),
        Ok(_) => Err(DomainError::Storage {
            message: format!(
                "Refusing to publish preflight run store temp file `{}` because it is not a regular file.",
                temp_path.display()
            ),
            repair: Some("Replace .ee/preflight_runs.json.tmp with a regular file.".to_owned()),
        }),
        Err(error) => Err(DomainError::Storage {
            message: format!(
                "Failed to stat preflight run store temp file `{}` before publish: {error}",
                temp_path.display()
            ),
            repair: Some("Check workspace .ee permissions.".to_owned()),
        }),
    }
}

fn ensure_preflight_run_store_final_path_for_write(store_path: &Path) -> Result<(), DomainError> {
    match fs::symlink_metadata(store_path) {
        Ok(metadata) if metadata.file_type().is_file() => Ok(()),
        Ok(_) => Err(DomainError::Storage {
            message: format!(
                "Refusing to write preflight run store `{}` because it is not a regular file.",
                store_path.display()
            ),
            repair: Some("Replace the preflight run store with a regular JSON file.".to_owned()),
        }),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(DomainError::Storage {
            message: format!(
                "Failed to stat preflight run store `{}` before write: {error}",
                store_path.display()
            ),
            repair: Some("Check workspace .ee permissions.".to_owned()),
        }),
    }
}

fn ensure_preflight_run_store_temp_path_for_write(temp_path: &Path) -> Result<(), DomainError> {
    match fs::symlink_metadata(temp_path) {
        Ok(metadata) if metadata.file_type().is_file() => Err(DomainError::Storage {
            message: format!(
                "Refusing to write preflight run store temp file `{}` because it already exists.",
                temp_path.display()
            ),
            repair: Some("Remove stale .ee/preflight_runs.json.tmp and retry.".to_owned()),
        }),
        Ok(_) => Err(DomainError::Storage {
            message: format!(
                "Refusing to write preflight run store temp file `{}` because it is not a regular file.",
                temp_path.display()
            ),
            repair: Some("Replace .ee/preflight_runs.json.tmp with a regular file.".to_owned()),
        }),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(DomainError::Storage {
            message: format!(
                "Failed to stat preflight run store temp file `{}` before write: {error}",
                temp_path.display()
            ),
            repair: Some("Check workspace .ee permissions.".to_owned()),
        }),
    }
}

fn write_preflight_run_store_temp_file(temp_path: &Path, text: &str) -> Result<(), DomainError> {
    let mut file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(temp_path)
        .map_err(|error| DomainError::Storage {
            message: format!(
                "Failed to create preflight run store temp file `{}`: {error}",
                temp_path.display()
            ),
            repair: Some("Check workspace .ee permissions.".to_owned()),
        })?;
    file.write_all(text.as_bytes())
        .map_err(|error| DomainError::Storage {
            message: format!(
                "Failed to write preflight run store temp file `{}`: {error}",
                temp_path.display()
            ),
            repair: Some("Check workspace .ee permissions.".to_owned()),
        })?;
    file.sync_all().map_err(|error| DomainError::Storage {
        message: format!(
            "Failed to sync preflight run store temp file `{}`: {error}",
            temp_path.display()
        ),
        repair: Some("Check workspace .ee permissions.".to_owned()),
    })
}

fn ensure_no_symlink_components(path: &Path, operation: &'static str) -> Result<(), DomainError> {
    let mut current = PathBuf::new();
    for component in path.components() {
        current.push(component.as_os_str());
        match fs::symlink_metadata(&current) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                return Err(DomainError::Storage {
                    message: format!(
                        "Refusing to {operation} preflight run store `{}` through symlinked path component `{}`.",
                        path.display(),
                        current.display()
                    ),
                    repair: Some(
                        "Replace the symlink with a real workspace .ee path before retrying."
                            .to_owned(),
                    ),
                });
            }
            Ok(_) => {}
            Err(error)
                if matches!(
                    error.kind(),
                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
                ) =>
            {
                return Ok(());
            }
            Err(error) => {
                return Err(DomainError::Storage {
                    message: format!(
                        "Failed to inspect preflight run store path component `{}` before {operation}: {error}",
                        current.display()
                    ),
                    repair: Some("Check workspace .ee permissions.".to_owned()),
                });
            }
        }
    }
    Ok(())
}

fn persist_preflight_run(workspace: &Path, report: &RunReport) -> Result<(), DomainError> {
    let store_path = preflight_run_store_path(workspace);
    let mut store = read_preflight_run_store(&store_path)?;
    match store
        .runs
        .iter_mut()
        .find(|stored| stored.report.run_id == report.run_id)
    {
        Some(stored) => stored.report = report.clone(),
        None => store.runs.push(StoredPreflightRun {
            report: report.clone(),
            close_report: None,
        }),
    }
    write_preflight_run_store(&store_path, &mut store)
}

fn preflight_run_view_from_report(report: &RunReport) -> PreflightRunView {
    PreflightRunView {
        id: report.run_id.clone(),
        task_input: report.task_input.clone(),
        status: report.status.clone(),
        risk_level: report.risk_level.clone(),
        cleared: report.cleared,
        block_reason: report.block_reason.clone(),
        started_at: report.started_at.clone(),
        completed_at: report.completed_at.clone(),
        duration_ms: None,
    }
}

/// Generate deterministic tripwires from already-selected evidence sources.
#[must_use]
pub fn generate_tripwires_from_sources(
    preflight_run_id: &str,
    task_input: &str,
    created_at: &str,
    sources: &[TripwireSource],
    config: &TripwireGenerationConfig,
) -> Vec<GeneratedTripwire> {
    if config.max_tripwires == 0 {
        return Vec::new();
    }

    let task_input = task_input.to_lowercase();
    let mut generated: Vec<_> = sources
        .iter()
        .filter(|source| source.score >= config.min_source_score)
        .filter(|source| source.matches_task(&task_input))
        .map(|source| build_generated_tripwire(preflight_run_id, created_at, source))
        .collect();

    generated.sort_by(|left, right| {
        risk_rank(right.risk_level)
            .cmp(&risk_rank(left.risk_level))
            .then_with(|| right.source_score.total_cmp(&left.source_score))
            .then_with(|| left.source_kind.rank().cmp(&right.source_kind.rank()))
            .then_with(|| left.source_id.cmp(&right.source_id))
    });
    generated.truncate(config.max_tripwires);
    generated
}

fn build_generated_tripwire(
    preflight_run_id: &str,
    created_at: &str,
    source: &TripwireSource,
) -> GeneratedTripwire {
    let id = stable_tripwire_id(preflight_run_id, source);
    let condition = tripwire_condition(source);
    let message = format!(
        "{} [{}:{}]: {}",
        source.risk_level.as_str(),
        source.kind.as_str(),
        source.source_id,
        source.summary
    );
    let tripwire = Tripwire::new(
        id,
        preflight_run_id,
        source.tripwire_type,
        condition,
        source.action,
        created_at,
    )
    .with_message(message);

    GeneratedTripwire {
        tripwire,
        source_kind: source.kind,
        source_id: source.source_id.clone(),
        source_score: source.score,
        trigger_terms: source.trigger_terms.clone(),
        provenance: vec![
            format!("source_kind={}", source.kind.as_str()),
            format!("source_id={}", source.source_id),
            format!("source_score={:.3}", source.score),
        ],
        risk_level: source.risk_level,
    }
}

fn stable_tripwire_id(preflight_run_id: &str, source: &TripwireSource) -> String {
    let mut hasher = blake3::Hasher::new();
    hasher.update(preflight_run_id.as_bytes());
    hasher.update(b"\0");
    hasher.update(source.kind.as_str().as_bytes());
    hasher.update(b"\0");
    hasher.update(source.source_id.as_bytes());
    hasher.update(b"\0");
    hasher.update(source.summary.as_bytes());
    let digest = hasher.finalize().to_hex().to_string();
    format!("{TRIPWIRE_ID_PREFIX}{}", &digest[..26])
}

fn tripwire_condition(source: &TripwireSource) -> String {
    if source.trigger_terms.is_empty() {
        return format!(
            "source:{}:{} remains relevant",
            source.kind.as_str(),
            source.source_id
        );
    }

    format!(
        "task_contains_any({})",
        source
            .trigger_terms
            .iter()
            .map(|term| format!("\"{term}\""))
            .collect::<Vec<_>>()
            .join(", ")
    )
}

fn normalize_terms<I, S>(terms: I) -> Vec<String>
where
    I: IntoIterator<Item = S>,
    S: Into<String>,
{
    let mut normalized: Vec<_> = terms
        .into_iter()
        .map(Into::into)
        .map(|term| term.trim().to_lowercase())
        .filter(|term| !term.is_empty())
        .collect();
    normalized.sort();
    normalized.dedup();
    normalized
}

fn normalized_score(score: f64) -> f64 {
    if score.is_finite() {
        score.clamp(0.0, 1.0)
    } else {
        0.0
    }
}

fn regret_profile(
    category: RegretCategory,
    score: f64,
) -> (RiskCategory, RiskLevel, TripwireAction) {
    match category {
        RegretCategory::Misinformation => (
            RiskCategory::Stability,
            if score >= 0.8 {
                RiskLevel::Critical
            } else {
                RiskLevel::High
            },
            if score >= 0.8 {
                TripwireAction::Halt
            } else {
                TripwireAction::Pause
            },
        ),
        RegretCategory::StaleInformation => (
            RiskCategory::Compliance,
            RiskLevel::High,
            TripwireAction::Pause,
        ),
        RegretCategory::MissingKnowledge | RegretCategory::RetrievalFailure => (
            RiskCategory::Stability,
            RiskLevel::High,
            TripwireAction::Pause,
        ),
        RegretCategory::UnderutilizedMemory | RegretCategory::Other => {
            (RiskCategory::Other, RiskLevel::Medium, TripwireAction::Warn)
        }
    }
}

fn claim_profile(status: ClaimStatus, score: f64) -> (RiskLevel, TripwireAction) {
    match status {
        ClaimStatus::Invalid | ClaimStatus::Regressed => (RiskLevel::High, TripwireAction::Pause),
        ClaimStatus::Expired | ClaimStatus::Stale => (RiskLevel::High, TripwireAction::Warn),
        ClaimStatus::Unverified | ClaimStatus::Draft => (RiskLevel::Medium, TripwireAction::Audit),
        ClaimStatus::Valid | ClaimStatus::Active | ClaimStatus::Verified => {
            if score >= 0.8 {
                (RiskLevel::Medium, TripwireAction::Warn)
            } else {
                (RiskLevel::Low, TripwireAction::Audit)
            }
        }
        ClaimStatus::Retired => (RiskLevel::Low, TripwireAction::Audit),
    }
}

fn risk_rank(level: RiskLevel) -> u8 {
    match level {
        RiskLevel::Critical => 5,
        RiskLevel::High => 4,
        RiskLevel::Medium => 3,
        RiskLevel::Low => 2,
        RiskLevel::None => 1,
        RiskLevel::Unknown => 0,
    }
}

/// Options for extracting an agent operating contract from repository docs.
#[derive(Clone, Debug)]
pub struct AgentOperatingContractOptions {
    /// Workspace path whose AGENTS.md and README.md should be inspected.
    pub workspace: PathBuf,
    /// Already-collected coordination and verification readiness snapshots.
    ///
    /// The extractor never probes live services itself; callers can populate
    /// this field from fixture data, Agent Mail, Beads/BV, git status, or RCH
    /// evidence they gathered before calling the read-only contract surface.
    pub readiness: AgentReadinessEvidenceInput,
}

impl Default for AgentOperatingContractOptions {
    fn default() -> Self {
        Self {
            workspace: PathBuf::from("."),
            readiness: AgentReadinessEvidenceInput::default(),
        }
    }
}

/// Machine-readable rule report for agent operating obligations.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AgentOperatingContractReport {
    pub schema: String,
    pub rules: Vec<AgentOperatingContractRule>,
    pub reporting_obligations: Vec<AgentOperatingContractReportingObligation>,
    pub readiness_evidence: Vec<AgentOperatingContractReadinessEvidence>,
    pub degraded: Vec<PreflightDegradation>,
}

impl AgentOperatingContractReport {
    #[must_use]
    pub fn new() -> Self {
        Self {
            schema: AGENT_OPERATING_CONTRACT_SCHEMA_V1.to_owned(),
            rules: Vec::new(),
            reporting_obligations: agent_operating_contract_reporting_obligations(
                &AgentReportingObligationInput::default(),
            ),
            readiness_evidence: agent_operating_contract_readiness_evidence(
                &AgentReadinessEvidenceInput::default(),
            ),
            degraded: Vec::new(),
        }
    }

    #[must_use]
    pub fn to_json(&self) -> String {
        crate::core::serialize_or_error(self)
    }
}

impl Default for AgentOperatingContractReport {
    fn default() -> Self {
        Self::new()
    }
}

/// One deterministic operating rule extracted from repository-local docs.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AgentOperatingContractRule {
    pub id: String,
    pub severity: String,
    pub category: String,
    pub source_file: String,
    pub source_heading: String,
    pub line_start: usize,
    pub line_end: usize,
    pub excerpt_hash: String,
    pub instruction: String,
}

/// One final-answer or handoff obligation agents must consider before
/// claiming work is complete. The list is compact enough to prepend into an
/// agent handoff and explicit enough for a later completion-audit adapter.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AgentOperatingContractReportingObligation {
    pub id: String,
    pub severity: String,
    pub obligation_type: String,
    pub trigger: String,
    pub instruction: String,
    pub evidence_kinds: Vec<String>,
    pub evidence_refs: Vec<String>,
    pub gap_code: Option<String>,
}

/// One coordination or verification substrate snapshot for deciding whether an
/// agent can safely edit or claim proof. The report stores evidence already
/// gathered by callers; it does not run live probes itself.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AgentOperatingContractReadinessEvidence {
    pub service: String,
    pub status: String,
    pub summary: String,
    pub evidence_refs: Vec<String>,
    pub metrics: Vec<AgentOperatingContractReadinessMetric>,
    pub degraded_codes: Vec<String>,
    pub next_action: Option<String>,
}

/// Deterministic string metric attached to a readiness evidence block.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AgentOperatingContractReadinessMetric {
    pub name: String,
    pub value: String,
}

/// Fixture-friendly evidence input for reporting-obligation evaluation.
/// Production integrations can populate this from Beads, Agent Mail, RCH, git
/// status, and memory citations without making the contract extractor itself
/// mutate or execute those substrates.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct AgentReportingObligationInput {
    pub code_changed: bool,
    pub rch_proof_refs: Vec<String>,
    pub dirty_tree: bool,
    pub unrelated_dirty_changes: bool,
    pub git_evidence_refs: Vec<String>,
    pub memory_used: bool,
    pub memory_citation_refs: Vec<String>,
    pub destructive_command_refs: Vec<String>,
    pub destructive_approval_refs: Vec<String>,
    pub coordination_refs: Vec<String>,
    pub command_bearing_evidence: bool,
    pub shell_safe_command_evidence_refs: Vec<String>,
    pub static_only_work: bool,
    pub static_check_refs: Vec<String>,
}

/// Fixture-friendly readiness input for coordination and verification
/// substrates. Callers populate these fields from already-collected probe
/// results; the preflight contract builder remains read-only and deterministic.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct AgentReadinessEvidenceInput {
    pub agent_mail: Option<AgentReadinessSourceInput>,
    pub beads: Option<AgentReadinessSourceInput>,
    pub bv: Option<AgentReadinessSourceInput>,
    pub tracker: Option<AgentReadinessSourceInput>,
    pub rch: Option<AgentReadinessSourceInput>,
}

/// Fixture input for one readiness source.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AgentReadinessSourceInput {
    pub status: AgentReadinessStatus,
    pub summary: String,
    pub evidence_refs: Vec<String>,
    pub metrics: Vec<AgentOperatingContractReadinessMetric>,
    pub degraded_codes: Vec<String>,
    pub next_action: Option<String>,
}

impl AgentReadinessSourceInput {
    #[must_use]
    pub fn new(status: AgentReadinessStatus, summary: impl Into<String>) -> Self {
        Self {
            status,
            summary: summary.into(),
            evidence_refs: Vec::new(),
            metrics: Vec::new(),
            degraded_codes: Vec::new(),
            next_action: None,
        }
    }
}

/// Stable readiness posture vocabulary for dynamic operating-contract evidence.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AgentReadinessStatus {
    NotCollected,
    Ok,
    Unavailable,
    Stale,
    Ambiguous,
    Blocked,
    Saturated,
    LocalOnly,
    Dirty,
}

impl AgentReadinessStatus {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::NotCollected => "not_collected",
            Self::Ok => "ok",
            Self::Unavailable => "unavailable",
            Self::Stale => "stale",
            Self::Ambiguous => "ambiguous",
            Self::Blocked => "blocked",
            Self::Saturated => "saturated",
            Self::LocalOnly => "local_only",
            Self::Dirty => "dirty",
        }
    }
}

#[derive(Clone, Copy, Debug)]
struct ReportingObligationTemplate {
    id: &'static str,
    severity: &'static str,
    obligation_type: &'static str,
    trigger: &'static str,
    instruction: &'static str,
    evidence_kinds: &'static [&'static str],
}

const REPORTING_OBLIGATION_TEMPLATES: &[ReportingObligationTemplate] = &[
    ReportingObligationTemplate {
        id: "agent.report.rch_proof",
        severity: "critical",
        obligation_type: "must_report",
        trigger: "code_or_rust_verification_changed",
        instruction: "Final answers and handoffs must state the RCH proof command/result or the exact remote-verification blocker; never imply local Cargo was run.",
        evidence_kinds: &["rch_proof_json", "beads_comment", "agent_mail_message"],
    },
    ReportingObligationTemplate {
        id: "agent.report.dirty_worktree",
        severity: "high",
        obligation_type: "must_report",
        trigger: "dirty_worktree_or_unrelated_changes_present",
        instruction: "Report dirty-tree caveats and distinguish own edits from unrelated active-agent changes.",
        evidence_kinds: &["git_status", "git_diff"],
    },
    ReportingObligationTemplate {
        id: "agent.report.destructive_command_audit",
        severity: "critical",
        obligation_type: "must_report",
        trigger: "destructive_or_denied_command_observed",
        instruction: "Report the exact destructive command, policy decision, approval text if any, and audit timestamp.",
        evidence_kinds: &[
            "preflight_guard_json",
            "human_approval_text",
            "session_note",
        ],
    },
    ReportingObligationTemplate {
        id: "agent.report.memory_citation",
        severity: "high",
        obligation_type: "must_report",
        trigger: "memory_derived_fact_used",
        instruction: "Cite memory-derived facts with the required memory citation block, or state that the fact is memory-derived and unverified.",
        evidence_kinds: &["memory_citation_block", "memory_source_path"],
    },
    ReportingObligationTemplate {
        id: "agent.report.coordination_evidence",
        severity: "medium",
        obligation_type: "advisory",
        trigger: "handoff_or_interrupted_work",
        instruction: "Prefer Beads comment ids, Agent Mail message ids, and RCH command hashes as compact handoff evidence.",
        evidence_kinds: &["beads_comment", "agent_mail_message", "rch_proof_json"],
    },
    ReportingObligationTemplate {
        id: "agent.report.shell_safe_command_evidence",
        severity: "high",
        obligation_type: "must_report",
        trigger: "command_bearing_tracker_or_mail_evidence",
        instruction: "Use file, stdin, direct MCP, or artifact-path transport for command-bearing Beads or Agent Mail evidence; never wrap evidence payloads in shell backticks or dollar-paren substitution.",
        evidence_kinds: &[
            "beads_comment",
            "agent_mail_message",
            "preflight_guard_json",
            "artifact_path",
        ],
    },
    ReportingObligationTemplate {
        id: "agent.report.static_only_work",
        severity: "low",
        obligation_type: "advisory",
        trigger: "static_only_or_docs_only_work",
        instruction: "For static-only work, say which non-Cargo checks were run and why Rust verification was not required.",
        evidence_kinds: &["rustfmt_or_schema_check", "git_diff_check"],
    },
];

#[must_use]
pub fn agent_operating_contract_reporting_obligations(
    input: &AgentReportingObligationInput,
) -> Vec<AgentOperatingContractReportingObligation> {
    REPORTING_OBLIGATION_TEMPLATES
        .iter()
        .map(|template| reporting_obligation_from_template(template, input))
        .collect()
}

fn reporting_obligation_from_template(
    template: &ReportingObligationTemplate,
    input: &AgentReportingObligationInput,
) -> AgentOperatingContractReportingObligation {
    let (evidence_refs, gap_code) = match template.id {
        "agent.report.rch_proof" => (
            input.rch_proof_refs.clone(),
            (input.code_changed && input.rch_proof_refs.is_empty()).then_some("missing_rch_proof"),
        ),
        "agent.report.dirty_worktree" => (
            input.git_evidence_refs.clone(),
            ((input.dirty_tree || input.unrelated_dirty_changes)
                && input.git_evidence_refs.is_empty())
            .then_some("dirty_worktree_caveat_required"),
        ),
        "agent.report.destructive_command_audit" => {
            let mut refs = input.destructive_command_refs.clone();
            refs.extend(input.destructive_approval_refs.clone());
            (
                refs,
                (!input.destructive_command_refs.is_empty()
                    && input.destructive_approval_refs.is_empty())
                .then_some("destructive_command_audit_required"),
            )
        }
        "agent.report.memory_citation" => (
            input.memory_citation_refs.clone(),
            (input.memory_used && input.memory_citation_refs.is_empty())
                .then_some("memory_citation_required"),
        ),
        "agent.report.coordination_evidence" => (input.coordination_refs.clone(), None),
        "agent.report.shell_safe_command_evidence" => (
            input.shell_safe_command_evidence_refs.clone(),
            (input.command_bearing_evidence && input.shell_safe_command_evidence_refs.is_empty())
                .then_some("shell_safe_command_evidence_required"),
        ),
        "agent.report.static_only_work" => (input.static_check_refs.clone(), None),
        _ => (Vec::new(), None),
    };

    AgentOperatingContractReportingObligation {
        id: template.id.to_owned(),
        severity: template.severity.to_owned(),
        obligation_type: template.obligation_type.to_owned(),
        trigger: template.trigger.to_owned(),
        instruction: template.instruction.to_owned(),
        evidence_kinds: template
            .evidence_kinds
            .iter()
            .map(|kind| (*kind).to_owned())
            .collect(),
        evidence_refs,
        gap_code: gap_code.map(str::to_owned),
    }
}

#[must_use]
pub fn agent_operating_contract_readiness_evidence(
    input: &AgentReadinessEvidenceInput,
) -> Vec<AgentOperatingContractReadinessEvidence> {
    [
        ("agent_mail", input.agent_mail.as_ref()),
        ("beads", input.beads.as_ref()),
        ("bv", input.bv.as_ref()),
        ("tracker", input.tracker.as_ref()),
        ("rch", input.rch.as_ref()),
    ]
    .into_iter()
    .map(|(service, source)| agent_readiness_evidence_for_service(service, source))
    .collect()
}

fn agent_readiness_evidence_for_service(
    service: &str,
    source: Option<&AgentReadinessSourceInput>,
) -> AgentOperatingContractReadinessEvidence {
    let Some(source) = source else {
        return AgentOperatingContractReadinessEvidence {
            service: service.to_owned(),
            status: AgentReadinessStatus::NotCollected.as_str().to_owned(),
            summary: "No readiness fixture or live-probe snapshot was supplied.".to_owned(),
            evidence_refs: Vec::new(),
            metrics: Vec::new(),
            degraded_codes: Vec::new(),
            next_action: None,
        };
    };

    AgentOperatingContractReadinessEvidence {
        service: service.to_owned(),
        status: source.status.as_str().to_owned(),
        summary: source.summary.clone(),
        evidence_refs: sorted_unique(source.evidence_refs.clone()),
        metrics: sorted_unique_metrics(source.metrics.clone()),
        degraded_codes: sorted_unique(readiness_degraded_codes(service, source)),
        next_action: source
            .next_action
            .clone()
            .or_else(|| readiness_default_next_action(service, source.status).map(str::to_owned)),
    }
}

fn readiness_degraded_codes(service: &str, source: &AgentReadinessSourceInput) -> Vec<String> {
    if !source.degraded_codes.is_empty() {
        return source.degraded_codes.clone();
    }

    readiness_default_degraded_code(service, source.status)
        .into_iter()
        .map(str::to_owned)
        .collect()
}

fn readiness_default_degraded_code(
    service: &str,
    status: AgentReadinessStatus,
) -> Option<&'static str> {
    match (service, status) {
        (_, AgentReadinessStatus::NotCollected | AgentReadinessStatus::Ok) => None,
        ("agent_mail", AgentReadinessStatus::Unavailable) => Some("agent_mail_unavailable"),
        ("agent_mail", AgentReadinessStatus::Stale | AgentReadinessStatus::Ambiguous) => {
            Some("coordination_source_stale")
        }
        ("beads", AgentReadinessStatus::Unavailable) => Some("beads_unavailable"),
        ("beads", AgentReadinessStatus::Stale | AgentReadinessStatus::Dirty) => {
            Some("beads_tracker_stale")
        }
        ("beads", AgentReadinessStatus::Ambiguous) => {
            Some("workspace_hygiene_beads_db_divergence_unknown")
        }
        ("bv", AgentReadinessStatus::Unavailable) => Some("bv_unavailable"),
        ("tracker", AgentReadinessStatus::Unavailable) => Some("beads_unavailable"),
        ("tracker", AgentReadinessStatus::Dirty | AgentReadinessStatus::Ambiguous) => {
            Some("workspace_hygiene_beads_db_divergence_unknown")
        }
        ("tracker", AgentReadinessStatus::Stale) => Some("beads_tracker_stale"),
        ("rch", AgentReadinessStatus::Unavailable) => Some("rch_unavailable"),
        ("rch", AgentReadinessStatus::Blocked | AgentReadinessStatus::Saturated) => {
            Some("rch_worker_topology_blocked")
        }
        ("rch", AgentReadinessStatus::LocalOnly) => Some("rch_remote_required_fallback_prevented"),
        (_, AgentReadinessStatus::Stale | AgentReadinessStatus::Ambiguous) => {
            Some("coordination_source_stale")
        }
        (_, AgentReadinessStatus::Unavailable | AgentReadinessStatus::Blocked) => {
            Some("coordination_source_unavailable")
        }
        (_, AgentReadinessStatus::Saturated | AgentReadinessStatus::LocalOnly) => {
            Some("coordination_source_unavailable")
        }
        (_, AgentReadinessStatus::Dirty) => Some("coordination_source_stale"),
    }
}

fn readiness_default_next_action(
    service: &str,
    status: AgentReadinessStatus,
) -> Option<&'static str> {
    match (service, status) {
        (_, AgentReadinessStatus::NotCollected | AgentReadinessStatus::Ok) => None,
        ("agent_mail", AgentReadinessStatus::Unavailable) => Some(
            "Refresh Agent Mail health or continue with Beads/local inspection and report the coordination gap.",
        ),
        ("agent_mail", AgentReadinessStatus::Stale | AgentReadinessStatus::Ambiguous) => Some(
            "Fetch a fresh Agent Mail inbox and reservation snapshot before claiming new work.",
        ),
        ("beads", AgentReadinessStatus::Unavailable) => {
            Some("Refresh Beads with br ready --json before selecting or closing work.")
        }
        ("beads", AgentReadinessStatus::Stale | AgentReadinessStatus::Ambiguous) => {
            Some("Refresh Beads state and record any stale tracker caveat before claiming work.")
        }
        ("tracker", AgentReadinessStatus::Dirty | AgentReadinessStatus::Ambiguous) => Some(
            "Report the dirty .beads/issues.jsonl caveat and avoid staging tracker metadata blindly.",
        ),
        ("tracker", AgentReadinessStatus::Stale) => {
            Some("Run br sync --flush-only only when intentionally exporting tracker updates.")
        }
        ("bv", AgentReadinessStatus::Unavailable) => Some(
            "Use br ready --json as the source of truth and record that BV ranking was unavailable.",
        ),
        ("rch", AgentReadinessStatus::Blocked) => Some(
            "Use scripts/rch_verify.sh --dry-run evidence and defer Rust proof until RCH topology is unblocked.",
        ),
        ("rch", AgentReadinessStatus::Saturated) => Some(
            "Defer heavy Cargo verification or wait for RCH capacity; do not fall back to local Cargo.",
        ),
        ("rch", AgentReadinessStatus::LocalOnly) => Some(
            "Refuse local Cargo fallback and rerun through RCH when remote workers are available.",
        ),
        ("rch", AgentReadinessStatus::Unavailable) => Some(
            "Record RCH unavailability and use non-Cargo static checks until remote verification is restored.",
        ),
        (_, AgentReadinessStatus::Dirty) => Some(
            "Record the dirty coordination source and refresh it before relying on the report.",
        ),
        (_, AgentReadinessStatus::Stale | AgentReadinessStatus::Ambiguous) => {
            Some("Refresh the coordination source before relying on this readiness snapshot.")
        }
        (_, AgentReadinessStatus::Unavailable | AgentReadinessStatus::Blocked) => Some(
            "Record the unavailable coordination source and continue only with explicit caveats.",
        ),
        (_, AgentReadinessStatus::Saturated | AgentReadinessStatus::LocalOnly) => {
            Some("Defer the affected verification or coordination step until the source recovers.")
        }
    }
}

fn sorted_unique(mut values: Vec<String>) -> Vec<String> {
    values.sort();
    values.dedup();
    values
}

fn sorted_unique_metrics(
    mut metrics: Vec<AgentOperatingContractReadinessMetric>,
) -> Vec<AgentOperatingContractReadinessMetric> {
    metrics.sort_by(|left, right| {
        left.name
            .cmp(&right.name)
            .then_with(|| left.value.cmp(&right.value))
    });
    metrics.dedup();
    metrics
}

#[derive(Clone, Copy, Debug)]
struct AgentContractRulePattern {
    id: &'static str,
    severity: &'static str,
    category: &'static str,
    instruction: &'static str,
    needles: &'static [&'static str],
}

const AGENT_CONTRACT_RULE_PATTERNS: &[AgentContractRulePattern] = &[
    AgentContractRulePattern {
        id: "agent.no_file_deletion",
        severity: "critical",
        category: "hard_denial",
        instruction: "Do not delete files or folders without explicit written human permission.",
        needles: &["no file deletion", "never allowed to delete a file"],
    },
    AgentContractRulePattern {
        id: "agent.no_worktrees",
        severity: "critical",
        category: "hard_denial",
        instruction: "Do not create or use git worktrees for this repository.",
        needles: &["no worktrees", "git worktree add"],
    },
    AgentContractRulePattern {
        id: "agent.no_git_reset_hard",
        severity: "critical",
        category: "hard_denial",
        instruction: "Do not run git reset --hard without exact explicit human authorization.",
        needles: &["git reset --hard"],
    },
    AgentContractRulePattern {
        id: "agent.no_git_stash",
        severity: "critical",
        category: "hard_denial",
        instruction: "Do not use git stash to park repository changes.",
        needles: &["never run `git stash`", "never run git stash"],
    },
    AgentContractRulePattern {
        id: "agent.no_git_checkout_other_ref",
        severity: "critical",
        category: "hard_denial",
        instruction: "Do not use git checkout to move off main or detach HEAD.",
        needles: &[
            "never run `git checkout <other-ref>`",
            "never run git checkout <other-ref>",
        ],
    },
    AgentContractRulePattern {
        id: "agent.no_script_based_code_changes",
        severity: "high",
        category: "hard_denial",
        instruction: "Make code edits manually; do not run scripts that transform code files.",
        needles: &[
            "no script-based changes",
            "processes/changes code files",
            "always make code changes manually",
        ],
    },
    AgentContractRulePattern {
        id: "agent.main_branch_only",
        severity: "high",
        category: "required_before_edit",
        instruction: "Keep repository work on the main branch and do not introduce master references.",
        needles: &["only use `main`", "default branch is `main`"],
    },
    AgentContractRulePattern {
        id: "agent.rch_remote_verification",
        severity: "critical",
        category: "required_before_verify",
        instruction: "Run Cargo builds, tests, clippy, and other CPU-heavy Rust verification through RCH only.",
        needles: &[
            "must be done using $rch",
            "rch-only",
            "no local cargo fallback",
        ],
    },
    AgentContractRulePattern {
        id: "agent.external_build_drive",
        severity: "high",
        category: "environment_fact",
        instruction: "Preserve the Mac external USB-NVMe Cargo target and temporary build routing.",
        needles: &[
            "external usb-nvme",
            "cargo_target_dir",
            "/volumes/usbnvme16tb",
        ],
    },
    AgentContractRulePattern {
        id: "agent.no_tokio_runtime",
        severity: "critical",
        category: "hard_denial",
        instruction: "Use Asupersync as the runtime; do not introduce Tokio.",
        needles: &["no tokio", "runtime is `/dp/asupersync`"],
    },
    AgentContractRulePattern {
        id: "agent.no_rusqlite_sqlx_diesel",
        severity: "critical",
        category: "hard_denial",
        instruction: "Use FrankenSQLite through SQLModel; do not introduce rusqlite, SQLx, Diesel, or SeaORM.",
        needles: &["no `rusqlite`", "no sqlx", "no diesel", "no seaorm"],
    },
    AgentContractRulePattern {
        id: "agent.no_petgraph",
        severity: "critical",
        category: "hard_denial",
        instruction: "Use FrankenNetworkX for graph analytics; do not introduce petgraph.",
        needles: &["no `petgraph`", "no petgraph"],
    },
    AgentContractRulePattern {
        id: "agent.stable_json",
        severity: "high",
        category: "reporting_required",
        instruction: "Machine-facing commands must keep stable versioned JSON output.",
        needles: &["stable json output", "stable json contract"],
    },
    AgentContractRulePattern {
        id: "agent.context_provenance",
        severity: "high",
        category: "reporting_required",
        instruction: "Generated context must include provenance and score or selection explanations.",
        needles: &[
            "provenance and score explanation",
            "provenance-tagged context",
        ],
    },
    AgentContractRulePattern {
        id: "agent.agent_mail_coordination",
        severity: "high",
        category: "coordination_required",
        instruction: "Coordinate with active agents through Agent Mail when it is available.",
        needles: &["agent mail", "file reservations"],
    },
    AgentContractRulePattern {
        id: "agent.beads_bv_triage",
        severity: "medium",
        category: "coordination_required",
        instruction: "Use Beads and BV for task tracking and prioritization instead of ad hoc selection.",
        needles: &["beads", "bv"],
    },
];

/// Extract the agent operating contract from the repository's AGENTS.md and README.md.
pub fn extract_agent_operating_contract(
    options: &AgentOperatingContractOptions,
) -> Result<AgentOperatingContractReport, DomainError> {
    let mut docs = Vec::new();
    let mut report = AgentOperatingContractReport::new();
    for file_name in ["AGENTS.md", "README.md"] {
        let path = options.workspace.join(file_name);
        match read_agent_contract_source_file(&path) {
            Ok(text) => docs.push((file_name.to_owned(), text)),
            Err(error) => report
                .degraded
                .push(agent_contract_source_unavailable(file_name, error)),
        }
    }

    let doc_refs = docs
        .iter()
        .map(|(source_file, text)| (source_file.as_str(), text.as_str()))
        .collect::<Vec<_>>();
    report.rules = extract_agent_operating_contract_rules(&doc_refs);
    report.readiness_evidence = agent_operating_contract_readiness_evidence(&options.readiness);
    Ok(report)
}

fn read_agent_contract_source_file(path: &Path) -> Result<String, std::io::Error> {
    let mut options = fs::OpenOptions::new();
    options.read(true);
    configure_agent_contract_source_open_no_follow(&mut options);
    let mut file = options.open(path)?;
    let metadata = file.metadata()?;
    if !metadata.is_file() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!(
                "agent operating contract source `{}` must be a regular file",
                path.display()
            ),
        ));
    }
    let mut text = String::new();
    file.read_to_string(&mut text)?;
    Ok(text)
}

#[cfg(all(unix, not(any(target_os = "espidf", target_os = "horizon"))))]
fn configure_agent_contract_source_open_no_follow(options: &mut fs::OpenOptions) {
    use std::os::unix::fs::OpenOptionsExt;

    options.custom_flags(rustix::fs::OFlags::NOFOLLOW.bits() as i32);
}

#[cfg(not(all(unix, not(any(target_os = "espidf", target_os = "horizon")))))]
fn configure_agent_contract_source_open_no_follow(_options: &mut fs::OpenOptions) {}

/// Extract operating rules from already-loaded markdown documents.
#[must_use]
pub fn extract_agent_operating_contract_rules(
    docs: &[(&str, &str)],
) -> Vec<AgentOperatingContractRule> {
    let mut rules_by_id = BTreeMap::new();
    for (source_file, text) in docs {
        extract_agent_operating_contract_rules_from_doc(source_file, text, &mut rules_by_id);
    }
    rules_by_id.into_values().collect()
}

fn extract_agent_operating_contract_rules_from_doc(
    source_file: &str,
    text: &str,
    rules_by_id: &mut BTreeMap<String, AgentOperatingContractRule>,
) {
    let mut current_heading = "document".to_owned();
    for (line_index, raw_line) in text.lines().enumerate() {
        let trimmed = raw_line.trim();
        if let Some(heading) = markdown_heading_text(trimmed) {
            current_heading = heading.to_owned();
            continue;
        }
        if trimmed.is_empty() {
            continue;
        }
        let normalized = trimmed.to_lowercase();
        for pattern in AGENT_CONTRACT_RULE_PATTERNS {
            if !pattern
                .needles
                .iter()
                .any(|needle| normalized.contains(needle))
            {
                continue;
            }
            rules_by_id.entry(pattern.id.to_owned()).or_insert_with(|| {
                AgentOperatingContractRule {
                    id: pattern.id.to_owned(),
                    severity: pattern.severity.to_owned(),
                    category: pattern.category.to_owned(),
                    source_file: source_file.to_owned(),
                    source_heading: current_heading.clone(),
                    line_start: line_index + 1,
                    line_end: line_index + 1,
                    excerpt_hash: excerpt_hash(trimmed),
                    instruction: pattern.instruction.to_owned(),
                }
            });
        }
    }
}

fn markdown_heading_text(line: &str) -> Option<&str> {
    let marker_count = line.chars().take_while(|ch| *ch == '#').count();
    if marker_count == 0 || marker_count > 6 {
        return None;
    }
    line.get(marker_count..)?
        .trim()
        .strip_prefix(' ')
        .or_else(|| {
            let rest = line.get(marker_count..)?.trim();
            (!rest.is_empty()).then_some(rest)
        })
}

fn excerpt_hash(excerpt: &str) -> String {
    let digest = blake3::hash(excerpt.as_bytes()).to_hex().to_string();
    format!("blake3:{}", &digest[..16])
}

fn agent_contract_source_unavailable(
    source_file: &str,
    error: std::io::Error,
) -> PreflightDegradation {
    PreflightDegradation {
        code: "agent_contract_source_unavailable".to_owned(),
        severity: "warning".to_owned(),
        message: format!(
            "Could not read {source_file} while extracting the agent operating contract: {error}"
        ),
        repair: Some(format!(
            "Restore readable {source_file} documentation or pass an explicit contract fixture."
        )),
    }
}

/// Run a preflight risk assessment.
pub fn run_preflight(options: &RunOptions) -> Result<RunReport, DomainError> {
    let started = Instant::now();
    trace_trauma_guard_preflight(&options.workspace, "input", 0, &[]);

    let run_id = format!("{}{}", PREFLIGHT_RUN_ID_PREFIX, generate_id());
    let mut report = RunReport::new(run_id.clone(), options.task_input.clone());
    report.dry_run = options.dry_run;

    let mut generated_tripwires = Vec::new();
    if options.check_tripwires {
        generated_tripwires = generate_tripwires_from_sources(
            &run_id,
            &options.task_input,
            &report.started_at,
            &options.tripwire_sources,
            &options.tripwire_generation,
        );
        report.tripwires_set = generated_tripwires.len();
        report.tripwires = generated_tripwires.iter().map(TripwireView::from).collect();
        report.evidence_ids = generated_tripwires
            .iter()
            .map(|generated| generated.source_id.clone())
            .collect();
    }

    if generated_tripwires.is_empty() {
        report.risk_level = RiskLevel::Unknown.as_str().to_owned();
        report.cleared = false;
        report.block_reason = Some(
            "No persisted preflight evidence matched the task; task-text heuristics are not enough to clear execution.".to_owned(),
        );
        report.next_action = "collect_preflight_evidence_or_use_risk_review_skill".to_owned();
        report.degraded.push(preflight_unavailable_degradation(
            &options.task_input,
            options.tripwire_sources.len(),
        ));
    } else {
        let risk_level = evidence_risk_level(&generated_tripwires);
        report.risk_level = risk_level.as_str().to_owned();
        report.risk_brief_id = Some(format!("{}{}", RISK_BRIEF_ID_PREFIX, generate_id()));

        let readiness = evidence_brief_fields(&generated_tripwires);
        report.top_risks = readiness.top_risks;
        report.must_verify_checks = readiness.must_verify_checks;
        report.risks_identified = report.top_risks.len();

        let auto_clear_threshold = options.auto_clear_threshold.unwrap_or(RiskLevel::Medium);
        if risk_level <= auto_clear_threshold {
            report.cleared = true;
        } else {
            report.cleared = false;
            report.block_reason = Some(format!(
                "Evidence-backed risk level {} exceeds auto-clear threshold {}",
                risk_level.as_str(),
                auto_clear_threshold.as_str()
            ));
        }
        report.next_action = if report.cleared {
            "proceed_after_evidence_review".to_owned()
        } else {
            "review_evidence_matches_before_proceeding".to_owned()
        };
    }
    if let Some(degradation) = stale_preflight_evidence_degradation(&options.workspace, &report)? {
        report.degraded.push(degradation);
        if report.next_action == "proceed_after_evidence_review" {
            report.next_action = "refresh_stale_preflight_evidence_before_proceeding".to_owned();
        }
    }

    report.status = PreflightStatus::Completed.as_str().to_owned();
    report.completed_at = Some(Utc::now().to_rfc3339());

    if options.persist_run && !options.dry_run {
        let degraded_codes = report
            .degraded
            .iter()
            .map(|degraded| degraded.code.as_str())
            .collect::<Vec<_>>();
        trace_trauma_guard_preflight(
            &options.workspace,
            "persistence",
            elapsed_ms_since(started),
            &degraded_codes,
        );
        persist_preflight_run(&options.workspace, &report)?;
    }

    let degraded_codes = report
        .degraded
        .iter()
        .map(|degraded| degraded.code.as_str())
        .collect::<Vec<_>>();
    trace_trauma_guard_preflight(
        &options.workspace,
        "response",
        elapsed_ms_since(started),
        &degraded_codes,
    );
    Ok(report)
}

/// Show details of a preflight run.
pub fn show_preflight(options: &ShowOptions) -> Result<ShowReport, DomainError> {
    validate_preflight_run_id(&options.run_id)?;
    let store_path = preflight_run_store_path(&options.workspace);
    let store = read_preflight_run_store(&store_path)?;
    let stored = store
        .runs
        .iter()
        .find(|stored| stored.report.run_id == options.run_id)
        .ok_or_else(|| preflight_run_not_found(&options.run_id))?;

    let mut report = ShowReport::new(preflight_run_view_from_report(&stored.report));
    if options.include_tripwires {
        report.tripwires = stored.report.tripwires.clone();
    }
    report.degraded = stored.report.degraded.clone();
    Ok(report)
}

/// Close a preflight run.
pub fn close_preflight(options: &CloseOptions) -> Result<CloseReport, DomainError> {
    validate_preflight_run_id(&options.run_id)?;
    let store_path = preflight_run_store_path(&options.workspace);
    let mut store = read_preflight_run_store(&store_path)?;
    let stored = store
        .runs
        .iter_mut()
        .find(|stored| stored.report.run_id == options.run_id)
        .ok_or_else(|| preflight_run_not_found(&options.run_id))?;

    let previous_status = stored
        .report
        .status
        .parse::<PreflightStatus>()
        .unwrap_or(PreflightStatus::Completed);
    let mut report = CloseReport::new(options.run_id.clone(), previous_status);
    report.cleared = options.cleared;
    report.reason = options.reason.clone();
    report.task_outcome = options
        .task_outcome
        .map(|outcome| outcome.as_str().to_owned());
    report.dry_run = options.dry_run;
    report.feedback = preflight_close_feedback(options)?;

    if !options.dry_run {
        stored.report.cleared = options.cleared;
        stored.report.block_reason = if options.cleared {
            None
        } else {
            options.reason.clone()
        };
        stored.report.status = PreflightStatus::Completed.as_str().to_owned();
        stored.close_report = Some(report.clone());
        write_preflight_run_store(&store_path, &mut store)?;
    }

    Ok(report)
}

fn preflight_close_feedback(
    options: &CloseOptions,
) -> Result<Option<RecordFeedbackReport>, DomainError> {
    let Some(task_outcome) = options
        .task_outcome
        .or_else(|| options.feedback_kind.map(|_| TaskOutcome::Unknown))
    else {
        return Ok(None);
    };
    let feedback_kind = options
        .feedback_kind
        .unwrap_or_else(|| infer_preflight_feedback_kind(options.cleared, task_outcome));
    let report = record_preflight_outcome(&RecordOutcomeOptions {
        workspace: options.workspace.clone(),
        preflight_run_id: options.run_id.clone(),
        task_outcome,
        feedback_kind,
        notes: options.reason.clone(),
        dry_run: options.dry_run,
    })?;
    Ok(Some(report))
}

fn validate_preflight_run_id(run_id: &str) -> Result<(), DomainError> {
    if run_id.starts_with(PREFLIGHT_RUN_ID_PREFIX) {
        Ok(())
    } else {
        // `run_id` is an unvalidated positional argument (`ee preflight
        // show|close <RUN_ID>`), so the preview must be taken on character
        // boundaries. Slicing `..len().min(3)` panicked whenever byte 3 fell
        // inside a multi-byte character — `ee preflight show 😀` aborted the
        // process instead of returning this usage error. Identical output for
        // ASCII input, which is every well-formed run ID.
        let preview: String = run_id.chars().take(3).collect();
        Err(DomainError::Usage {
            message: format!(
                "Invalid preflight run ID: expected prefix '{PREFLIGHT_RUN_ID_PREFIX}', got '{preview}'"
            ),
            repair: Some("Provide a valid preflight run ID (format: pf_<uuid>)".to_owned()),
        })
    }
}

fn preflight_run_not_found(run_id: &str) -> DomainError {
    DomainError::NotFound {
        resource: "preflight run".to_owned(),
        id: run_id.to_owned(),
        repair: Some(
            "Run `ee preflight run <task>` in the same workspace before show/close.".to_owned(),
        ),
    }
}

/// Assess risk level from task input text.
fn assess_task_risk(task_input: &str) -> RiskLevel {
    let lower = task_input.to_lowercase();

    // Critical risk patterns
    if lower.contains("delete")
        || lower.contains("rm -rf")
        || matches_drop_table_sql(task_input)
        || lower.contains("truncate")
    {
        return RiskLevel::Critical;
    }

    // High risk patterns
    if lower.contains("production")
        || lower.contains("deploy")
        || lower.contains("migrate")
        || lower.contains("force")
    {
        return RiskLevel::High;
    }

    // Medium risk patterns
    if lower.contains("update")
        || lower.contains("modify")
        || lower.contains("change")
        || lower.contains("refactor")
    {
        return RiskLevel::Medium;
    }

    // Low risk patterns
    if lower.contains("read")
        || lower.contains("list")
        || lower.contains("show")
        || lower.contains("search")
    {
        return RiskLevel::Low;
    }

    RiskLevel::None
}

struct ReadinessBriefFields {
    top_risks: Vec<String>,
    must_verify_checks: Vec<String>,
}

fn evidence_brief_fields(generated_tripwires: &[GeneratedTripwire]) -> ReadinessBriefFields {
    let top_risks = generated_tripwires
        .iter()
        .map(|generated| {
            generated.tripwire.message.clone().unwrap_or_else(|| {
                format!(
                    "{} [{}:{}]",
                    generated.risk_level.as_str(),
                    generated.source_kind.as_str(),
                    generated.source_id
                )
            })
        })
        .collect();
    let must_verify_checks = generated_tripwires
        .iter()
        .map(|generated| {
            format!(
                "Review evidence source {}:{} before proceeding.",
                generated.source_kind.as_str(),
                generated.source_id
            )
        })
        .collect();
    ReadinessBriefFields {
        top_risks,
        must_verify_checks,
    }
}

fn evidence_risk_level(generated_tripwires: &[GeneratedTripwire]) -> RiskLevel {
    generated_tripwires
        .iter()
        .map(|generated| generated.risk_level)
        .max_by_key(|level| risk_rank(*level))
        .unwrap_or(RiskLevel::Unknown)
}

fn preflight_unavailable_degradation(
    task_input: &str,
    source_count: usize,
) -> PreflightDegradation {
    let heuristic_level = assess_task_risk(task_input);
    let source_message = if source_count == 0 {
        "No persisted evidence sources were provided."
    } else {
        "Persisted evidence sources were provided, but none matched the task and threshold."
    };
    let heuristic_message = if matches!(heuristic_level, RiskLevel::None | RiskLevel::Unknown) {
        "No task-text heuristic is treated as an evidence-backed risk."
    } else {
        "Task text matched heuristic risk language, but heuristics are not treated as evidence-backed risks."
    };
    PreflightDegradation::evidence_unavailable(format!("{source_message} {heuristic_message}"))
}

fn stale_preflight_evidence_degradation(
    workspace: &Path,
    report: &RunReport,
) -> Result<Option<PreflightDegradation>, DomainError> {
    let store_path = preflight_run_store_path(workspace);
    let store = read_preflight_run_store(&store_path)?;
    let now = Utc::now();
    let stale_before = now - Duration::days(DEFAULT_STALE_EVIDENCE_DAYS);
    let latest_matching = store
        .runs
        .iter()
        .filter(|stored| stored.report.task_input == report.task_input)
        .filter(|stored| stored.report.run_id != report.run_id)
        .filter_map(|stored| {
            preflight_report_observed_at(&stored.report).map(|observed_at| (stored, observed_at))
        })
        .max_by(|(_, left), (_, right)| left.cmp(right));

    let Some((stored, observed_at)) = latest_matching else {
        return Ok(None);
    };
    if observed_at >= stale_before {
        return Ok(None);
    }

    Ok(Some(PreflightDegradation::evidence_stale(format!(
        "Persisted preflight evidence for this task is stale: previous run {} was observed at {}.",
        stored.report.run_id,
        observed_at.to_rfc3339()
    ))))
}

fn preflight_report_observed_at(report: &RunReport) -> Option<DateTime<Utc>> {
    let timestamp = report.completed_at.as_deref().unwrap_or(&report.started_at);
    DateTime::parse_from_rfc3339(timestamp)
        .ok()
        .map(|parsed| parsed.with_timezone(&Utc))
}

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

    type TestResult = Result<(), String>;

    fn ensure<T: std::fmt::Debug + PartialEq>(actual: T, expected: T, ctx: &str) -> TestResult {
        if actual == expected {
            Ok(())
        } else {
            Err(format!("{ctx}: expected {expected:?}, got {actual:?}"))
        }
    }

    fn temp_workspace() -> Result<tempfile::TempDir, String> {
        tempfile::tempdir().map_err(|error| format!("tempdir: {error}"))
    }

    #[derive(Debug, serde::Serialize)]
    struct AgentContractGoldenProjection {
        schema: String,
        fixture: String,
        rule_count: usize,
        rule_ids: Vec<String>,
        categories: Vec<String>,
        reporting_obligation_count: usize,
        reporting_obligation_ids: Vec<String>,
        reporting_obligation_types: Vec<String>,
        reporting_gap_codes: Vec<String>,
        readiness_service_count: usize,
        readiness_services: Vec<String>,
        readiness_statuses: Vec<String>,
        readiness_degraded_codes: Vec<String>,
        degraded_codes: Vec<String>,
    }

    fn agent_contract_golden_projection(
        fixture: &str,
        report: &AgentOperatingContractReport,
    ) -> AgentContractGoldenProjection {
        let mut rule_ids = report
            .rules
            .iter()
            .map(|rule| rule.id.clone())
            .collect::<Vec<_>>();
        rule_ids.sort();
        let mut categories = report
            .rules
            .iter()
            .map(|rule| rule.category.clone())
            .collect::<Vec<_>>();
        categories.sort();
        categories.dedup();
        let mut reporting_obligation_ids = report
            .reporting_obligations
            .iter()
            .map(|obligation| obligation.id.clone())
            .collect::<Vec<_>>();
        reporting_obligation_ids.sort();
        let mut reporting_obligation_types = report
            .reporting_obligations
            .iter()
            .map(|obligation| obligation.obligation_type.clone())
            .collect::<Vec<_>>();
        reporting_obligation_types.sort();
        reporting_obligation_types.dedup();
        let mut reporting_gap_codes = report
            .reporting_obligations
            .iter()
            .filter_map(|obligation| obligation.gap_code.clone())
            .collect::<Vec<_>>();
        reporting_gap_codes.sort();
        reporting_gap_codes.dedup();
        let mut readiness_services = report
            .readiness_evidence
            .iter()
            .map(|evidence| evidence.service.clone())
            .collect::<Vec<_>>();
        readiness_services.sort();
        let mut readiness_statuses = report
            .readiness_evidence
            .iter()
            .map(|evidence| format!("{}:{}", evidence.service, evidence.status))
            .collect::<Vec<_>>();
        readiness_statuses.sort();
        let mut readiness_degraded_codes = report
            .readiness_evidence
            .iter()
            .flat_map(|evidence| evidence.degraded_codes.clone())
            .collect::<Vec<_>>();
        readiness_degraded_codes.sort();
        readiness_degraded_codes.dedup();
        let mut degraded_codes = report
            .degraded
            .iter()
            .map(|entry| entry.code.clone())
            .collect::<Vec<_>>();
        degraded_codes.sort();
        degraded_codes.dedup();

        AgentContractGoldenProjection {
            schema: report.schema.clone(),
            fixture: fixture.to_owned(),
            rule_count: report.rules.len(),
            rule_ids,
            categories,
            reporting_obligation_count: report.reporting_obligations.len(),
            reporting_obligation_ids,
            reporting_obligation_types,
            reporting_gap_codes,
            readiness_service_count: report.readiness_evidence.len(),
            readiness_services,
            readiness_statuses,
            readiness_degraded_codes,
            degraded_codes,
        }
    }

    fn assert_agent_contract_golden(
        name: &str,
        actual: &AgentContractGoldenProjection,
    ) -> TestResult {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/golden/preflight")
            .join(name);
        let expected_text = std::fs::read_to_string(&path)
            .map_err(|error| format!("read {}: {error}", path.display()))?;
        let expected: serde_json::Value = serde_json::from_str(&expected_text)
            .map_err(|error| format!("parse {}: {error}", path.display()))?;
        let actual_text = serde_json::to_string_pretty(actual)
            .map_err(|error| format!("serialize golden projection: {error}"))?;
        let actual_value: serde_json::Value = serde_json::from_str(&actual_text)
            .map_err(|error| format!("parse actual projection: {error}"))?;
        ensure(actual_value, expected, name)
    }

    #[test]
    fn run_dry_run_completes_immediately() -> TestResult {
        let options = RunOptions {
            task_input: "test task".to_owned(),
            dry_run: true,
            ..Default::default()
        };

        let report = run_preflight(&options).map_err(|e| e.message())?;
        ensure(report.dry_run, true, "dry_run")?;
        ensure(
            report.status,
            PreflightStatus::Completed.as_str().to_owned(),
            "status",
        )?;
        ensure(
            report.run_id.starts_with(PREFLIGHT_RUN_ID_PREFIX),
            true,
            "run_id prefix",
        )
    }

    #[test]
    fn run_without_evidence_does_not_promote_task_text_to_risk() -> TestResult {
        let options = RunOptions {
            task_input: "delete all production data".to_owned(),
            dry_run: false,
            ..Default::default()
        };

        let report = run_preflight(&options).map_err(|e| e.message())?;
        ensure(
            report.risk_level,
            RiskLevel::Unknown.as_str().to_owned(),
            "task-text-only risk level",
        )?;
        ensure(report.cleared, false, "should not be cleared")?;
        ensure(report.risk_brief_id.is_none(), true, "no fake risk brief")?;
        ensure(report.top_risks.is_empty(), true, "no heuristic risks")?;
        ensure(
            report.ask_now_prompts.is_empty(),
            true,
            "no ask-now prompts",
        )?;
        ensure(
            report
                .degraded
                .iter()
                .any(|entry| entry.code == "preflight_evidence_unavailable"),
            true,
            "evidence unavailable degradation",
        )
    }

    #[test]
    fn run_with_no_evidence_does_not_auto_clear_low_risk_text() -> TestResult {
        let options = RunOptions {
            task_input: "list all files".to_owned(),
            dry_run: false,
            ..Default::default()
        };

        let report = run_preflight(&options).map_err(|e| e.message())?;
        ensure(
            report.risk_level,
            RiskLevel::Unknown.as_str().to_owned(),
            "risk_level",
        )?;
        ensure(report.cleared, false, "no evidence means not cleared")
    }

    #[test]
    fn show_rejects_invalid_run_id() -> TestResult {
        let options = ShowOptions {
            run_id: "invalid_id".to_owned(),
            ..Default::default()
        };

        let result = show_preflight(&options);
        ensure(result.is_err(), true, "should reject invalid ID")
    }

    #[test]
    fn close_returns_not_found_without_persisted_run() -> TestResult {
        let options = CloseOptions {
            run_id: format!("{}test", PREFLIGHT_RUN_ID_PREFIX),
            cleared: true,
            ..Default::default()
        };

        let Err(error) = close_preflight(&options) else {
            return Err("close should not invent a persisted preflight run".to_owned());
        };
        ensure(error.code(), "not_found", "error code")
    }

    #[test]
    fn persisted_run_can_be_shown_with_tripwire_provenance() -> TestResult {
        let workspace = temp_workspace()?;
        let source = TripwireSource::dependency_contract(
            "dep_forbidden_runtime",
            "Forbidden runtime dependency must not be introduced",
            true,
            ["release"],
        );
        let run = run_preflight(&RunOptions {
            workspace: workspace.path().to_path_buf(),
            task_input: "prepare release".to_owned(),
            persist_run: true,
            tripwire_sources: vec![source],
            ..Default::default()
        })
        .map_err(|error| error.message())?;

        ensure(
            preflight_run_store_path(workspace.path()).exists(),
            true,
            "run store exists",
        )?;

        let shown = show_preflight(&ShowOptions {
            workspace: workspace.path().to_path_buf(),
            run_id: run.run_id.clone(),
            include_tripwires: true,
            ..Default::default()
        })
        .map_err(|error| error.message())?;

        ensure(shown.run.id, run.run_id, "shown run id")?;
        ensure(shown.tripwires.len(), 1, "shown tripwire count")?;
        ensure(
            shown.tripwires[0].source_id.clone(),
            Some("dep_forbidden_runtime".to_owned()),
            "shown source id",
        )?;
        ensure(shown.degraded.is_empty(), true, "no degraded evidence")
    }

    #[cfg(unix)]
    #[test]
    fn run_preflight_rejects_symlinked_metadata_parent() -> TestResult {
        use std::os::unix::fs::symlink;

        let workspace = temp_workspace()?;
        let real_metadata = workspace.path().join("real-ee");
        std::fs::create_dir_all(&real_metadata).map_err(|error| error.to_string())?;
        symlink(&real_metadata, workspace.path().join(".ee")).map_err(|error| error.to_string())?;

        let source = TripwireSource::dependency_contract(
            "dep_forbidden_runtime",
            "Forbidden runtime dependency must not be introduced",
            true,
            ["release"],
        );
        let result = run_preflight(&RunOptions {
            workspace: workspace.path().to_path_buf(),
            task_input: "prepare release".to_owned(),
            persist_run: true,
            tripwire_sources: vec![source],
            ..Default::default()
        });
        let error = result.expect_err("symlinked .ee parent should be rejected");
        ensure(
            error.message().contains("symlinked path component"),
            true,
            "symlinked .ee error message",
        )?;
        ensure(
            real_metadata.join("preflight_runs.json").exists(),
            false,
            "preflight store must not be written through symlinked .ee parent",
        )
    }

    #[cfg(unix)]
    #[test]
    fn show_preflight_rejects_symlinked_run_store_file() -> TestResult {
        use std::os::unix::fs::symlink;

        let workspace = temp_workspace()?;
        let ee_dir = workspace.path().join(".ee");
        std::fs::create_dir_all(&ee_dir).map_err(|error| error.to_string())?;

        let outside_store = workspace.path().join("outside-preflight-runs.json");
        let run = RunReport::new(
            "pf_symlink000000000000000000000".to_owned(),
            "prepare release".to_owned(),
        );
        let mut store = PreflightRunStoreDocument {
            schema: PREFLIGHT_RUN_STORE_SCHEMA_V1.to_owned(),
            runs: vec![StoredPreflightRun {
                report: run,
                close_report: None,
            }],
        };
        write_preflight_run_store(&outside_store, &mut store).map_err(|error| error.message())?;
        symlink(&outside_store, preflight_run_store_path(workspace.path()))
            .map_err(|error| error.to_string())?;

        let result = show_preflight(&ShowOptions {
            workspace: workspace.path().to_path_buf(),
            run_id: "pf_symlink000000000000000000000".to_owned(),
            ..Default::default()
        });
        let error = result.expect_err("symlinked preflight run store should be rejected");
        ensure(
            error.message().contains("symlinked path component"),
            true,
            "symlinked store error message",
        )
    }

    #[cfg(unix)]
    #[test]
    fn preflight_run_store_final_read_open_rejects_swapped_symlink_file() -> TestResult {
        use std::os::unix::fs::symlink;

        let workspace = temp_workspace()?;
        let ee_dir = workspace.path().join(".ee");
        std::fs::create_dir_all(&ee_dir).map_err(|error| error.to_string())?;
        let outside_store = workspace.path().join("outside-preflight-runs.json");
        let outside_text =
            format!("{{\"schema\":\"{PREFLIGHT_RUN_STORE_SCHEMA_V1}\",\"runs\":[]}}\n");
        std::fs::write(&outside_store, &outside_text).map_err(|error| error.to_string())?;
        let store_path = preflight_run_store_path(workspace.path());
        symlink(&outside_store, &store_path).map_err(|error| error.to_string())?;

        let error = open_preflight_run_store_file_for_read(&store_path)
            .expect_err("final preflight run-store read open must reject symlinks");

        ensure(
            error.kind() != std::io::ErrorKind::NotFound,
            true,
            "final symlink read should fail because the path is a symlink",
        )?;
        ensure(
            std::fs::read_to_string(&outside_store).map_err(|error| error.to_string())?,
            outside_text,
            "preflight run-store read helper must not follow the symlink target",
        )
    }

    #[test]
    fn show_preflight_rejects_non_regular_run_store_file() -> TestResult {
        let workspace = temp_workspace()?;
        std::fs::create_dir_all(preflight_run_store_path(workspace.path()))
            .map_err(|error| error.to_string())?;

        let result = show_preflight(&ShowOptions {
            workspace: workspace.path().to_path_buf(),
            run_id: "pf_directory000000000000000000".to_owned(),
            ..Default::default()
        });
        let error = result.expect_err("directory preflight run store should be rejected");
        ensure(
            error.message().contains("not a regular file"),
            true,
            "non-regular store error message",
        )
    }

    #[test]
    fn write_preflight_run_store_rejects_non_regular_final_path() -> TestResult {
        let workspace = temp_workspace()?;
        let store_path = preflight_run_store_path(workspace.path());
        std::fs::create_dir_all(&store_path).map_err(|error| error.to_string())?;

        let mut store = PreflightRunStoreDocument::default();
        let result = write_preflight_run_store(&store_path, &mut store);
        let error = result.expect_err("directory preflight run store should be rejected on write");
        ensure(
            error.message().contains("not a regular file"),
            true,
            "non-regular write error message",
        )?;
        ensure(
            store_path.is_dir(),
            true,
            "non-regular store path remains a directory",
        )
    }

    #[test]
    fn write_preflight_run_store_rejects_existing_regular_temp_file_without_truncating()
    -> TestResult {
        let workspace = temp_workspace()?;
        let store_path = preflight_run_store_path(workspace.path());
        let temp_path = store_path.with_extension("json.tmp");
        std::fs::create_dir_all(temp_path.parent().expect("preflight temp parent"))
            .map_err(|error| error.to_string())?;
        std::fs::write(&temp_path, "stale preflight temp").map_err(|error| error.to_string())?;

        let mut store = PreflightRunStoreDocument::default();
        let result = write_preflight_run_store(&store_path, &mut store);
        let error =
            result.expect_err("existing regular temp file should reject preflight store write");
        ensure(
            error.message().contains("already exists"),
            true,
            "existing temp error message",
        )?;
        ensure(
            std::fs::read_to_string(&temp_path).map_err(|error| error.to_string())?,
            "stale preflight temp".to_owned(),
            "existing temp content remains unchanged",
        )?;
        ensure(
            store_path.exists(),
            false,
            "final preflight store must not be published when temp exists",
        )
    }

    #[cfg(unix)]
    #[test]
    fn write_preflight_run_store_rechecks_final_symlink_before_publish() -> TestResult {
        use std::os::unix::fs::symlink;

        let workspace = temp_workspace()?;
        let store_path = preflight_run_store_path(workspace.path());
        let temp_path = store_path.with_extension("json.tmp");
        std::fs::create_dir_all(temp_path.parent().expect("preflight temp parent"))
            .map_err(|error| error.to_string())?;
        write_preflight_run_store_temp_file(&temp_path, "{\"schema\":\"sentinel\"}\n")
            .map_err(|error| error.message())?;

        let outside_store = workspace.path().join("outside-preflight-runs.json");
        std::fs::write(&outside_store, "outside sentinel").map_err(|error| error.to_string())?;
        symlink(&outside_store, &store_path).map_err(|error| error.to_string())?;

        let result = publish_preflight_run_store_temp_file(&temp_path, &store_path);
        let error = result.expect_err("final symlink must be rejected before publish");
        ensure(
            error.message().contains("symlinked path component"),
            true,
            "final symlink publish error message",
        )?;
        ensure(
            std::fs::read_to_string(&outside_store).map_err(|error| error.to_string())?,
            "outside sentinel".to_owned(),
            "outside symlink target remains unchanged",
        )?;
        ensure(
            std::fs::read_to_string(&temp_path).map_err(|error| error.to_string())?,
            "{\"schema\":\"sentinel\"}\n".to_owned(),
            "temp store remains available after rejected publish",
        )
    }

    #[cfg(unix)]
    #[test]
    fn write_preflight_run_store_rechecks_temp_symlink_before_publish() -> TestResult {
        use std::os::unix::fs::symlink;

        let workspace = temp_workspace()?;
        let store_path = preflight_run_store_path(workspace.path());
        let temp_path = store_path.with_extension("json.tmp");
        let preserved_temp = store_path.with_extension("json.tmp.preserved");
        std::fs::create_dir_all(temp_path.parent().expect("preflight temp parent"))
            .map_err(|error| error.to_string())?;
        write_preflight_run_store_temp_file(&temp_path, "{\"schema\":\"sentinel\"}\n")
            .map_err(|error| error.message())?;
        std::fs::rename(&temp_path, &preserved_temp).map_err(|error| error.to_string())?;

        let outside_store = workspace.path().join("outside-preflight-runs.json");
        std::fs::write(&outside_store, "outside sentinel").map_err(|error| error.to_string())?;
        symlink(&outside_store, &temp_path).map_err(|error| error.to_string())?;

        let result = publish_preflight_run_store_temp_file(&temp_path, &store_path);
        let error = result.expect_err("temp symlink must be rejected before publish");
        ensure(
            error.message().contains("symlinked path component")
                || error.message().contains("not a regular file"),
            true,
            "temp symlink publish error message",
        )?;
        ensure(
            store_path.exists(),
            false,
            "final preflight store must not be published through swapped temp symlink",
        )?;
        ensure(
            std::fs::read_to_string(&outside_store).map_err(|error| error.to_string())?,
            "outside sentinel".to_owned(),
            "outside symlink target remains unchanged",
        )?;
        ensure(
            std::fs::symlink_metadata(&temp_path)
                .map_err(|error| error.to_string())?
                .file_type()
                .is_symlink(),
            true,
            "rejected temp symlink remains for inspection",
        )?;
        ensure(
            std::fs::read_to_string(&preserved_temp).map_err(|error| error.to_string())?,
            "{\"schema\":\"sentinel\"}\n".to_owned(),
            "preserved temp store remains available after simulated swap",
        )
    }

    #[test]
    fn run_reports_matching_stale_persisted_preflight_evidence() -> TestResult {
        let workspace = temp_workspace()?;
        let mut stale_report = RunReport::new(
            "pf_stale000000000000000000000000".to_owned(),
            "prepare release".to_owned(),
        );
        stale_report.status = PreflightStatus::Completed.as_str().to_owned();
        stale_report.started_at = "2000-01-01T00:00:00Z".to_owned();
        stale_report.completed_at = Some("2000-01-01T00:00:01Z".to_owned());

        let mut store = PreflightRunStoreDocument::default();
        store.runs.push(StoredPreflightRun {
            report: stale_report,
            close_report: None,
        });
        write_preflight_run_store(&preflight_run_store_path(workspace.path()), &mut store)
            .map_err(|error| error.message())?;

        let report = run_preflight(&RunOptions {
            workspace: workspace.path().to_path_buf(),
            task_input: "prepare release".to_owned(),
            persist_run: false,
            ..Default::default()
        })
        .map_err(|error| error.message())?;

        ensure(
            report
                .degraded
                .iter()
                .any(|entry| entry.code == "preflight_evidence_stale"),
            true,
            "stale evidence degradation present",
        )
    }

    #[test]
    fn agent_operating_contract_extraction_is_stable_and_deduped() -> TestResult {
        let docs = [(
            "AGENTS.md",
            r#"# Root Rules

## Git Branch: ONLY Use `main`, NEVER `master`

The default branch is `main`.

## RULE NUMBER 2: NO WORKTREES. EVER. NO EXCEPTIONS.

Never run `git worktree add`.
Never run `git worktree add`.

## Compiler Checks

All cargo builds and tests and other CPU intensive operations MUST be done using $rch.
"#,
        )];

        let first = extract_agent_operating_contract_rules(&docs);
        let second = extract_agent_operating_contract_rules(&docs);

        ensure(first.clone(), second, "stable extraction")?;
        ensure(
            first
                .iter()
                .filter(|rule| rule.id == "agent.no_worktrees")
                .count(),
            1,
            "duplicate rule id collapsed",
        )?;
        let ids = first
            .iter()
            .map(|rule| rule.id.as_str())
            .collect::<Vec<_>>();
        ensure(
            ids,
            vec![
                "agent.main_branch_only",
                "agent.no_worktrees",
                "agent.rch_remote_verification",
            ],
            "deterministic sorted rule ids",
        )?;
        let no_worktrees = first
            .iter()
            .find(|rule| rule.id == "agent.no_worktrees")
            .ok_or_else(|| "missing no-worktrees rule".to_owned())?;
        ensure(
            no_worktrees.source_heading.clone(),
            "RULE NUMBER 2: NO WORKTREES. EVER. NO EXCEPTIONS.".to_owned(),
            "source heading",
        )?;
        ensure(no_worktrees.line_start, 9, "line_start")
    }

    #[test]
    fn agent_operating_contract_extracts_readme_hard_requirements() -> TestResult {
        let docs = [(
            "README.md",
            r#"# Eidetic Engine

## Hard Requirements

- Runtime is `/dp/asupersync`. **No Tokio.** Anywhere. Ever.
- Database is `/dp/frankensqlite` through `/dp/sqlmodel_rust`. **No `rusqlite`, no SQLx, no Diesel, no SeaORM.**
- Graph is `/dp/franken_networkx`. **No `petgraph`.**
- Every machine-facing command supports stable JSON output.
- Every generated context includes provenance and score explanation.
"#,
        )];

        let rules = extract_agent_operating_contract_rules(&docs);
        let ids = rules
            .iter()
            .map(|rule| rule.id.as_str())
            .collect::<Vec<_>>();
        ensure(
            ids,
            vec![
                "agent.context_provenance",
                "agent.no_petgraph",
                "agent.no_rusqlite_sqlx_diesel",
                "agent.no_tokio_runtime",
                "agent.stable_json",
            ],
            "README hard requirement rule ids",
        )?;
        ensure(
            rules
                .iter()
                .all(|rule| rule.source_heading == "Hard Requirements"),
            true,
            "README source headings",
        )
    }

    #[test]
    fn agent_operating_contract_source_heading_tracks_heading_changes() -> TestResult {
        let old_docs = [(
            "AGENTS.md",
            r#"# AGENTS

## Old Safety Heading

RULE NUMBER 2: NO WORKTREES. EVER.
"#,
        )];
        let new_docs = [(
            "AGENTS.md",
            r#"# AGENTS

## New Safety Heading

RULE NUMBER 2: NO WORKTREES. EVER.
"#,
        )];

        let old_rules = extract_agent_operating_contract_rules(&old_docs);
        let new_rules = extract_agent_operating_contract_rules(&new_docs);
        let old_rule = old_rules
            .iter()
            .find(|rule| rule.id == "agent.no_worktrees")
            .ok_or_else(|| "missing old no-worktrees rule".to_owned())?;
        let new_rule = new_rules
            .iter()
            .find(|rule| rule.id == "agent.no_worktrees")
            .ok_or_else(|| "missing new no-worktrees rule".to_owned())?;

        ensure(old_rule.id.clone(), new_rule.id.clone(), "stable rule id")?;
        ensure(
            old_rule.source_heading.clone(),
            "Old Safety Heading".to_owned(),
            "old source heading",
        )?;
        ensure(
            new_rule.source_heading.clone(),
            "New Safety Heading".to_owned(),
            "new source heading",
        )
    }

    #[test]
    fn agent_operating_contract_reports_missing_docs_as_degraded() -> TestResult {
        let workspace = temp_workspace()?;
        std::fs::write(
            workspace.path().join("AGENTS.md"),
            "# AGENTS\n\nNo Tokio.\n",
        )
        .map_err(|error| error.to_string())?;

        let report = extract_agent_operating_contract(&AgentOperatingContractOptions {
            workspace: workspace.path().to_path_buf(),
            ..AgentOperatingContractOptions::default()
        })
        .map_err(|error| error.message())?;

        ensure(
            report.schema.clone(),
            AGENT_OPERATING_CONTRACT_SCHEMA_V1.to_owned(),
            "schema",
        )?;
        ensure(
            report
                .degraded
                .iter()
                .any(|entry| entry.code == "agent_contract_source_unavailable"),
            true,
            "missing README degradation",
        )?;
        ensure(
            report
                .rules
                .iter()
                .any(|rule| rule.id == "agent.no_tokio_runtime"),
            true,
            "extracts available AGENTS rule",
        )
    }

    #[cfg(unix)]
    #[test]
    fn agent_operating_contract_rejects_symlinked_doc_sources() -> TestResult {
        use std::os::unix::fs::symlink;

        let workspace = temp_workspace()?;
        let outside = tempfile::tempdir().map_err(|error| error.to_string())?;
        let outside_agents = outside.path().join("AGENTS.md");
        let outside_readme = outside.path().join("README.md");
        std::fs::write(
            &outside_agents,
            "# Outside AGENTS\n\nNever run `git worktree add`.\n",
        )
        .map_err(|error| error.to_string())?;
        std::fs::write(
            &outside_readme,
            "# Outside README\n\nEvery machine-facing command supports stable JSON output.\n",
        )
        .map_err(|error| error.to_string())?;
        symlink(&outside_agents, workspace.path().join("AGENTS.md"))
            .map_err(|error| error.to_string())?;
        symlink(&outside_readme, workspace.path().join("README.md"))
            .map_err(|error| error.to_string())?;

        let report = extract_agent_operating_contract(&AgentOperatingContractOptions {
            workspace: workspace.path().to_path_buf(),
            ..AgentOperatingContractOptions::default()
        })
        .map_err(|error| error.message())?;

        ensure(
            report.rules.is_empty(),
            true,
            "symlinked docs must not be parsed as workspace contract sources",
        )?;
        ensure(
            report
                .degraded
                .iter()
                .filter(|entry| entry.code == "agent_contract_source_unavailable")
                .count(),
            2,
            "both symlinked docs are reported unavailable",
        )
    }

    #[test]
    fn agent_operating_contract_extracts_supplied_readiness_evidence() -> TestResult {
        let workspace = temp_workspace()?;
        std::fs::write(
            workspace.path().join("AGENTS.md"),
            "# AGENTS\n\nRULE NUMBER 1: NO FILE DELETION.\n",
        )
        .map_err(|error| error.to_string())?;
        std::fs::write(
            workspace.path().join("README.md"),
            "# README\n\nEvery machine-facing command supports stable JSON output.\n",
        )
        .map_err(|error| error.to_string())?;

        let report = extract_agent_operating_contract(&AgentOperatingContractOptions {
            workspace: workspace.path().to_path_buf(),
            readiness: AgentReadinessEvidenceInput {
                agent_mail: Some(readiness_source(
                    AgentReadinessStatus::Ok,
                    "Agent Mail snapshot supplied by caller.",
                    &[("ack_required_count", "0")],
                )),
                rch: Some(readiness_source(
                    AgentReadinessStatus::LocalOnly,
                    "RCH snapshot says only local fallback is available.",
                    &[("workers_healthy", "0")],
                )),
                ..AgentReadinessEvidenceInput::default()
            },
        })
        .map_err(|error| error.message())?;
        let readiness = report
            .readiness_evidence
            .iter()
            .map(|entry| (entry.service.as_str(), entry))
            .collect::<BTreeMap<_, _>>();
        let agent_mail = readiness
            .get("agent_mail")
            .ok_or_else(|| "missing Agent Mail readiness".to_owned())?;
        let rch = readiness
            .get("rch")
            .ok_or_else(|| "missing RCH readiness".to_owned())?;

        ensure(
            agent_mail.status.clone(),
            "ok".to_owned(),
            "supplied Agent Mail status",
        )?;
        ensure(
            agent_mail.metrics[0].name.clone(),
            "ack_required_count".to_owned(),
            "supplied Agent Mail metric",
        )?;
        ensure(
            rch.status.clone(),
            "local_only".to_owned(),
            "supplied RCH status",
        )?;
        ensure(
            rch.degraded_codes.clone(),
            vec!["rch_remote_required_fallback_prevented".to_owned()],
            "supplied RCH default degraded code",
        )
    }

    #[test]
    fn agent_operating_contract_reporting_obligations_flag_missing_rch_proof() -> TestResult {
        let obligations =
            agent_operating_contract_reporting_obligations(&AgentReportingObligationInput {
                code_changed: true,
                ..AgentReportingObligationInput::default()
            });
        let rch = obligations
            .iter()
            .find(|obligation| obligation.id == "agent.report.rch_proof")
            .ok_or_else(|| "missing RCH reporting obligation".to_owned())?;

        ensure(
            rch.obligation_type.clone(),
            "must_report".to_owned(),
            "RCH obligation type",
        )?;
        ensure(
            rch.gap_code.clone(),
            Some("missing_rch_proof".to_owned()),
            "RCH proof gap",
        )
    }

    #[test]
    fn agent_operating_contract_reporting_obligations_flag_memory_citation_gap() -> TestResult {
        let obligations =
            agent_operating_contract_reporting_obligations(&AgentReportingObligationInput {
                memory_used: true,
                ..AgentReportingObligationInput::default()
            });
        let memory = obligations
            .iter()
            .find(|obligation| obligation.id == "agent.report.memory_citation")
            .ok_or_else(|| "missing memory citation obligation".to_owned())?;

        ensure(
            memory.gap_code.clone(),
            Some("memory_citation_required".to_owned()),
            "memory citation gap",
        )
    }

    #[test]
    fn agent_operating_contract_reporting_obligations_flag_dirty_tree_caveat_gap() -> TestResult {
        let obligations =
            agent_operating_contract_reporting_obligations(&AgentReportingObligationInput {
                dirty_tree: true,
                unrelated_dirty_changes: true,
                ..AgentReportingObligationInput::default()
            });
        let dirty = obligations
            .iter()
            .find(|obligation| obligation.id == "agent.report.dirty_worktree")
            .ok_or_else(|| "missing dirty-worktree obligation".to_owned())?;

        ensure(
            dirty.gap_code.clone(),
            Some("dirty_worktree_caveat_required".to_owned()),
            "dirty tree gap",
        )
    }

    #[test]
    fn agent_operating_contract_reporting_obligations_flag_destructive_command_audit_gap()
    -> TestResult {
        let obligations =
            agent_operating_contract_reporting_obligations(&AgentReportingObligationInput {
                destructive_command_refs: vec!["preflight_guard_json:cmd123".to_owned()],
                ..AgentReportingObligationInput::default()
            });
        let destructive = obligations
            .iter()
            .find(|obligation| obligation.id == "agent.report.destructive_command_audit")
            .ok_or_else(|| "missing destructive-command obligation".to_owned())?;

        ensure(
            destructive.gap_code.clone(),
            Some("destructive_command_audit_required".to_owned()),
            "destructive command gap",
        )
    }

    #[test]
    fn agent_operating_contract_reporting_obligations_flag_shell_safe_command_evidence_gap()
    -> TestResult {
        let obligations =
            agent_operating_contract_reporting_obligations(&AgentReportingObligationInput {
                command_bearing_evidence: true,
                ..AgentReportingObligationInput::default()
            });
        let shell_safe = obligations
            .iter()
            .find(|obligation| obligation.id == "agent.report.shell_safe_command_evidence")
            .ok_or_else(|| "missing shell-safe command evidence obligation".to_owned())?;

        ensure(
            shell_safe.obligation_type.clone(),
            "must_report".to_owned(),
            "shell-safe command evidence obligation type",
        )?;
        ensure(
            shell_safe.gap_code.clone(),
            Some("shell_safe_command_evidence_required".to_owned()),
            "shell-safe command evidence gap",
        )
    }

    #[test]
    fn agent_operating_contract_schema_allows_all_reporting_gap_codes() -> TestResult {
        let schema_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("docs/schemas/ee.agent_operating_contract.v1.json");
        let schema_text = std::fs::read_to_string(&schema_path)
            .map_err(|error| format!("read {}: {error}", schema_path.display()))?;
        let schema: serde_json::Value = serde_json::from_str(&schema_text)
            .map_err(|error| format!("parse {}: {error}", schema_path.display()))?;
        let allowed = schema
            .pointer("/properties/reporting_obligations/items/properties/gap_code/enum")
            .and_then(serde_json::Value::as_array)
            .ok_or_else(|| "schema gap_code enum missing".to_owned())?
            .iter()
            .filter_map(serde_json::Value::as_str)
            .collect::<std::collections::BTreeSet<_>>();
        let emitted_gap_codes = [
            AgentReportingObligationInput {
                code_changed: true,
                ..AgentReportingObligationInput::default()
            },
            AgentReportingObligationInput {
                dirty_tree: true,
                ..AgentReportingObligationInput::default()
            },
            AgentReportingObligationInput {
                destructive_command_refs: vec!["preflight_guard_json:cmd123".to_owned()],
                ..AgentReportingObligationInput::default()
            },
            AgentReportingObligationInput {
                memory_used: true,
                ..AgentReportingObligationInput::default()
            },
            AgentReportingObligationInput {
                command_bearing_evidence: true,
                ..AgentReportingObligationInput::default()
            },
        ]
        .iter()
        .flat_map(agent_operating_contract_reporting_obligations)
        .filter_map(|obligation| obligation.gap_code)
        .collect::<std::collections::BTreeSet<_>>();

        for code in emitted_gap_codes {
            if !allowed.contains(code.as_str()) {
                return Err(format!(
                    "schema gap_code enum must allow emitted gap code `{code}`"
                ));
            }
        }
        Ok(())
    }

    #[test]
    fn agent_operating_contract_reporting_obligations_preserve_shell_safe_command_evidence()
    -> TestResult {
        let obligations =
            agent_operating_contract_reporting_obligations(&AgentReportingObligationInput {
                command_bearing_evidence: true,
                shell_safe_command_evidence_refs: vec![
                    "beads_comment:4188".to_owned(),
                    "agent_mail_message:6002".to_owned(),
                ],
                ..AgentReportingObligationInput::default()
            });
        let shell_safe = obligations
            .iter()
            .find(|obligation| obligation.id == "agent.report.shell_safe_command_evidence")
            .ok_or_else(|| "missing shell-safe command evidence obligation".to_owned())?;

        ensure(
            shell_safe.evidence_refs.clone(),
            vec![
                "beads_comment:4188".to_owned(),
                "agent_mail_message:6002".to_owned(),
            ],
            "shell-safe evidence refs",
        )?;
        ensure(
            shell_safe.gap_code.clone(),
            None,
            "shell-safe evidence gap cleared",
        )
    }

    #[test]
    fn agent_operating_contract_reporting_obligations_preserve_clean_static_only_evidence()
    -> TestResult {
        let obligations =
            agent_operating_contract_reporting_obligations(&AgentReportingObligationInput {
                static_only_work: true,
                static_check_refs: vec![
                    "rustfmt:src/core/preflight.rs".to_owned(),
                    "git_diff_check".to_owned(),
                ],
                ..AgentReportingObligationInput::default()
            });
        let static_only = obligations
            .iter()
            .find(|obligation| obligation.id == "agent.report.static_only_work")
            .ok_or_else(|| "missing static-only obligation".to_owned())?;

        ensure(
            static_only.obligation_type.clone(),
            "advisory".to_owned(),
            "static-only type",
        )?;
        ensure(
            static_only.evidence_refs.clone(),
            vec![
                "rustfmt:src/core/preflight.rs".to_owned(),
                "git_diff_check".to_owned(),
            ],
            "static check refs",
        )?;
        ensure(static_only.gap_code.clone(), None, "static-only gap")
    }

    #[test]
    fn agent_operating_contract_readiness_defaults_to_not_collected() -> TestResult {
        let readiness =
            agent_operating_contract_readiness_evidence(&AgentReadinessEvidenceInput::default());
        let statuses = readiness
            .iter()
            .map(|entry| format!("{}:{}", entry.service, entry.status))
            .collect::<Vec<_>>();

        ensure(
            statuses,
            vec![
                "agent_mail:not_collected".to_owned(),
                "beads:not_collected".to_owned(),
                "bv:not_collected".to_owned(),
                "tracker:not_collected".to_owned(),
                "rch:not_collected".to_owned(),
            ],
            "default readiness statuses",
        )?;
        ensure(
            readiness
                .iter()
                .all(|entry| entry.degraded_codes.is_empty()),
            true,
            "not-collected readiness is static-safe",
        )
    }

    #[test]
    fn agent_operating_contract_readiness_preserves_fixture_evidence_sorted() -> TestResult {
        let mut rch = AgentReadinessSourceInput::new(
            AgentReadinessStatus::Blocked,
            "RCH workers are healthy but path topology blocks remote-required Cargo.",
        );
        rch.evidence_refs = vec![
            "rch:status".to_owned(),
            "beads:comment-4242".to_owned(),
            "rch:status".to_owned(),
        ];
        rch.metrics = vec![
            AgentOperatingContractReadinessMetric {
                name: "workers_healthy".to_owned(),
                value: "5".to_owned(),
            },
            AgentOperatingContractReadinessMetric {
                name: "active_builds".to_owned(),
                value: "1".to_owned(),
            },
        ];
        rch.degraded_codes = vec![
            "rch_remote_required_fallback_prevented".to_owned(),
            "rch_worker_topology_blocked".to_owned(),
            "rch_worker_topology_blocked".to_owned(),
        ];
        rch.next_action =
            Some("Use scripts/rch_verify.sh dry-run proof until topology is fixed.".to_owned());

        let readiness = agent_operating_contract_readiness_evidence(&AgentReadinessEvidenceInput {
            rch: Some(rch),
            ..AgentReadinessEvidenceInput::default()
        });
        let rch = readiness
            .iter()
            .find(|entry| entry.service == "rch")
            .ok_or_else(|| "missing RCH readiness block".to_owned())?;

        ensure(rch.status.clone(), "blocked".to_owned(), "RCH status")?;
        ensure(
            rch.evidence_refs.clone(),
            vec!["beads:comment-4242".to_owned(), "rch:status".to_owned()],
            "sorted unique evidence refs",
        )?;
        ensure(
            rch.metrics
                .iter()
                .map(|metric| format!("{}={}", metric.name, metric.value))
                .collect::<Vec<_>>(),
            vec!["active_builds=1".to_owned(), "workers_healthy=5".to_owned()],
            "sorted metrics",
        )?;
        ensure(
            rch.degraded_codes.clone(),
            vec![
                "rch_remote_required_fallback_prevented".to_owned(),
                "rch_worker_topology_blocked".to_owned(),
            ],
            "sorted unique RCH degraded codes",
        )?;
        ensure(
            rch.next_action.clone(),
            Some("Use scripts/rch_verify.sh dry-run proof until topology is fixed.".to_owned()),
            "caller supplied RCH next action is preserved",
        )
    }

    #[test]
    fn agent_operating_contract_readiness_defaults_degraded_codes_for_bad_postures() -> TestResult {
        let readiness = agent_operating_contract_readiness_evidence(&AgentReadinessEvidenceInput {
            agent_mail: Some(AgentReadinessSourceInput::new(
                AgentReadinessStatus::Unavailable,
                "Agent Mail probe failed.",
            )),
            tracker: Some(AgentReadinessSourceInput::new(
                AgentReadinessStatus::Dirty,
                ".beads/issues.jsonl is dirty or divergence is ambiguous.",
            )),
            rch: Some(AgentReadinessSourceInput::new(
                AgentReadinessStatus::LocalOnly,
                "RCH would fall back local, which is denied.",
            )),
            ..AgentReadinessEvidenceInput::default()
        });
        let degraded_by_service = readiness
            .iter()
            .map(|entry| (entry.service.as_str(), entry.degraded_codes.clone()))
            .collect::<BTreeMap<_, _>>();

        ensure(
            degraded_by_service.get("agent_mail").cloned(),
            Some(vec!["agent_mail_unavailable".to_owned()]),
            "agent mail default degraded code",
        )?;
        ensure(
            degraded_by_service.get("tracker").cloned(),
            Some(vec![
                "workspace_hygiene_beads_db_divergence_unknown".to_owned(),
            ]),
            "tracker dirty default degraded code",
        )?;
        ensure(
            degraded_by_service.get("rch").cloned(),
            Some(vec!["rch_remote_required_fallback_prevented".to_owned()]),
            "RCH local-only default degraded code",
        )?;
        let next_actions = readiness
            .iter()
            .map(|entry| (entry.service.as_str(), entry.next_action.clone()))
            .collect::<BTreeMap<_, _>>();
        ensure(
            next_actions
                .get("agent_mail")
                .cloned()
                .flatten()
                .is_some_and(|action| action.contains("Agent Mail health")),
            true,
            "agent mail default next action",
        )?;
        ensure(
            next_actions
                .get("tracker")
                .cloned()
                .flatten()
                .is_some_and(|action| action.contains(".beads/issues.jsonl")),
            true,
            "tracker dirty default next action",
        )?;
        ensure(
            next_actions
                .get("rch")
                .cloned()
                .flatten()
                .is_some_and(|action| action.contains("Refuse local Cargo fallback")),
            true,
            "RCH local-only default next action",
        )
    }

    #[test]
    fn agent_operating_contract_readiness_accepts_all_services_healthy() -> TestResult {
        let readiness = agent_operating_contract_readiness_evidence(&AgentReadinessEvidenceInput {
            agent_mail: Some(readiness_source(
                AgentReadinessStatus::Ok,
                "Agent Mail available for SandyTern.",
                &[
                    ("ack_required_count", "0"),
                    ("active_reservation_count", "0"),
                ],
            )),
            beads: Some(readiness_source(
                AgentReadinessStatus::Ok,
                "Beads ready queue and sync state are current.",
                &[("ready_count", "12"), ("stale_count", "0")],
            )),
            bv: Some(readiness_source(
                AgentReadinessStatus::Ok,
                "BV robot triage returned a ranked top pick.",
                &[("top_pick_count", "1")],
            )),
            tracker: Some(readiness_source(
                AgentReadinessStatus::Ok,
                "Tracker export is clean for this contract fixture.",
                &[("dirty_tracker_paths", "0")],
            )),
            rch: Some(readiness_source(
                AgentReadinessStatus::Ok,
                "RCH has remote workers and local fallback is not needed.",
                &[("workers_healthy", "5"), ("queued_builds", "0")],
            )),
        });

        ensure(readiness.len(), 5, "healthy readiness service count")?;
        ensure(
            readiness
                .iter()
                .all(|entry| entry.status == "ok" && entry.degraded_codes.is_empty()),
            true,
            "healthy readiness has no degraded codes",
        )?;
        ensure(
            readiness
                .iter()
                .all(|entry| entry.next_action.is_none() && !entry.metrics.is_empty()),
            true,
            "healthy readiness carries metrics and no repair action",
        )
    }

    #[test]
    fn agent_operating_contract_readiness_covers_beads_stale_and_rch_saturated() -> TestResult {
        let readiness = agent_operating_contract_readiness_evidence(&AgentReadinessEvidenceInput {
            beads: Some(readiness_source(
                AgentReadinessStatus::Stale,
                "Beads export is older than the live database.",
                &[("stale_count", "3")],
            )),
            rch: Some(readiness_source(
                AgentReadinessStatus::Saturated,
                "RCH workers are healthy but verifier queue capacity is exhausted.",
                &[("workers_healthy", "5"), ("slots_available", "0")],
            )),
            ..AgentReadinessEvidenceInput::default()
        });
        let by_service = readiness
            .iter()
            .map(|entry| (entry.service.as_str(), entry))
            .collect::<BTreeMap<_, _>>();

        let beads = by_service
            .get("beads")
            .ok_or_else(|| "missing Beads readiness block".to_owned())?;
        ensure(
            beads.status.clone(),
            "stale".to_owned(),
            "Beads stale status",
        )?;
        ensure(
            beads.degraded_codes.clone(),
            vec!["beads_tracker_stale".to_owned()],
            "Beads stale degraded code",
        )?;

        let rch = by_service
            .get("rch")
            .ok_or_else(|| "missing RCH readiness block".to_owned())?;
        ensure(
            rch.status.clone(),
            "saturated".to_owned(),
            "RCH saturated status",
        )?;
        ensure(
            rch.degraded_codes.clone(),
            vec!["rch_worker_topology_blocked".to_owned()],
            "RCH saturated degraded code",
        )?;
        ensure(
            rch.next_action
                .clone()
                .is_some_and(|action| action.contains("RCH capacity")),
            true,
            "RCH saturated default next action",
        )
    }

    fn readiness_source(
        status: AgentReadinessStatus,
        summary: &str,
        metrics: &[(&str, &str)],
    ) -> AgentReadinessSourceInput {
        let mut source = AgentReadinessSourceInput::new(status, summary);
        source.evidence_refs = vec![format!("fixture:{}", status.as_str())];
        source.metrics = metrics
            .iter()
            .map(|(name, value)| AgentOperatingContractReadinessMetric {
                name: (*name).to_owned(),
                value: (*value).to_owned(),
            })
            .collect();
        source
    }

    #[test]
    fn agent_operating_contract_minimal_workspace_matches_golden() -> TestResult {
        let docs = [
            (
                "AGENTS.md",
                r#"# Minimal Agent Rules

## Safety

RULE NUMBER 1: NO FILE DELETION.
RULE NUMBER 2: NO WORKTREES. EVER.
"#,
            ),
            (
                "README.md",
                r#"# Minimal README

## Hard Requirements

- Runtime is `/dp/asupersync`. **No Tokio.** Anywhere. Ever.
- Every machine-facing command supports stable JSON output.
- Every generated context includes provenance and score explanation.
"#,
            ),
        ];
        let report = AgentOperatingContractReport {
            schema: AGENT_OPERATING_CONTRACT_SCHEMA_V1.to_owned(),
            rules: extract_agent_operating_contract_rules(&docs),
            reporting_obligations: agent_operating_contract_reporting_obligations(
                &AgentReportingObligationInput::default(),
            ),
            readiness_evidence: agent_operating_contract_readiness_evidence(
                &AgentReadinessEvidenceInput::default(),
            ),
            degraded: Vec::new(),
        };

        assert_agent_contract_golden(
            "agent_operating_contract_minimal.json.golden",
            &agent_contract_golden_projection("minimal_workspace", &report),
        )
    }

    #[test]
    fn agent_operating_contract_repository_projection_matches_golden() -> TestResult {
        let report = extract_agent_operating_contract(&AgentOperatingContractOptions {
            workspace: PathBuf::from(env!("CARGO_MANIFEST_DIR")),
            ..AgentOperatingContractOptions::default()
        })
        .map_err(|error| error.message())?;

        assert_agent_contract_golden(
            "agent_operating_contract_repository.json.golden",
            &agent_contract_golden_projection("eidetic_engine_cli_repository", &report),
        )
    }

    #[test]
    fn close_updates_persisted_run_state() -> TestResult {
        let workspace = temp_workspace()?;
        let source = TripwireSource::dependency_contract(
            "dep_forbidden_runtime",
            "Forbidden runtime dependency must not be introduced",
            true,
            ["release"],
        );
        let run = run_preflight(&RunOptions {
            workspace: workspace.path().to_path_buf(),
            task_input: "prepare release".to_owned(),
            persist_run: true,
            tripwire_sources: vec![source],
            ..Default::default()
        })
        .map_err(|error| error.message())?;

        let close = close_preflight(&CloseOptions {
            workspace: workspace.path().to_path_buf(),
            run_id: run.run_id.clone(),
            cleared: false,
            reason: Some("manual review still required".to_owned()),
            task_outcome: Some(TaskOutcome::Failure),
            feedback_kind: Some(PreflightFeedbackKind::Missed),
            ..Default::default()
        })
        .map_err(|error| error.message())?;

        ensure(close.run_id, run.run_id.clone(), "close run id")?;
        ensure(close.cleared, false, "close cleared")?;
        ensure(
            close.task_outcome,
            Some("failure".to_owned()),
            "close task outcome",
        )?;
        let feedback = close
            .feedback
            .as_ref()
            .ok_or_else(|| "close feedback report missing".to_owned())?;
        ensure(
            feedback.preflight_run_id.clone(),
            run.run_id.clone(),
            "close feedback preflight run id",
        )?;
        ensure(
            feedback.task_outcome.clone(),
            "failure".to_owned(),
            "close feedback task outcome",
        )?;
        ensure(
            feedback.feedback_kind.clone(),
            Some("missed".to_owned()),
            "close feedback kind",
        )?;
        ensure(
            feedback.signal.clone(),
            "harmful".to_owned(),
            "close feedback signal",
        )?;
        ensure(
            feedback.record_status.clone(),
            "evaluated".to_owned(),
            "close feedback record status",
        )?;
        ensure(
            feedback.record_id.is_some(),
            true,
            "close feedback receives durable record id",
        )?;

        let shown = show_preflight(&ShowOptions {
            workspace: workspace.path().to_path_buf(),
            run_id: run.run_id.clone(),
            ..Default::default()
        })
        .map_err(|error| error.message())?;

        ensure(shown.run.cleared, false, "stored cleared")?;
        ensure(
            shown.run.block_reason,
            Some("manual review still required".to_owned()),
            "stored close reason",
        )?;

        let store = read_preflight_run_store(&preflight_run_store_path(workspace.path()))
            .map_err(|error| error.message())?;
        let stored_close = store
            .runs
            .iter()
            .find(|stored| stored.report.run_id == run.run_id)
            .and_then(|stored| stored.close_report.as_ref())
            .ok_or_else(|| "stored close report missing".to_owned())?;
        let stored_feedback = stored_close
            .feedback
            .as_ref()
            .ok_or_else(|| "stored close feedback missing".to_owned())?;
        ensure(
            stored_feedback.task_outcome.clone(),
            "failure".to_owned(),
            "stored close feedback task outcome",
        )?;
        ensure(
            stored_feedback.feedback_kind.clone(),
            Some("missed".to_owned()),
            "stored close feedback kind",
        )?;
        ensure(
            stored_feedback.signal.clone(),
            "harmful".to_owned(),
            "stored close feedback signal",
        )
    }

    #[test]
    fn report_serializes_to_json() -> TestResult {
        let report = RunReport::new("pf_test".to_owned(), "test task".to_owned());
        let json = report.to_json();
        ensure(json.contains("pf_test"), true, "json contains run_id")?;
        ensure(
            json.contains(PREFLIGHT_REPORT_SCHEMA_V1),
            true,
            "json contains schema",
        )
    }

    #[test]
    fn assess_task_risk_patterns() -> TestResult {
        ensure(assess_task_risk("rm -rf /"), RiskLevel::Critical, "rm -rf")?;
        ensure(
            assess_task_risk("DROP/**/TABLE memories"),
            RiskLevel::Critical,
            "drop table comment bypass",
        )?;
        ensure(
            assess_task_risk("deploy to production"),
            RiskLevel::High,
            "production deploy",
        )?;
        ensure(
            assess_task_risk("refactor the module"),
            RiskLevel::Medium,
            "refactor",
        )?;
        ensure(
            assess_task_risk("search for files"),
            RiskLevel::Low,
            "search",
        )?;
        ensure(
            assess_task_risk("hello world"),
            RiskLevel::None,
            "no pattern",
        )
    }

    #[test]
    fn tripwire_source_normalizes_terms_and_scores() -> TestResult {
        let source = TripwireSource::high_utility_memory(
            "mem_release_rule",
            "Run release checks before publishing",
            f64::NAN,
            [" Release ", "", "release"],
        );

        ensure(source.score, 0.0, "non-finite score clamps to zero")?;
        ensure(
            source.trigger_terms,
            vec!["release".to_string()],
            "normalized terms",
        )
    }

    #[test]
    fn generate_tripwires_filters_orders_and_stabilizes_ids() -> TestResult {
        let sources = vec![
            TripwireSource::high_utility_memory(
                "mem_release_rule",
                "Run release checks before publishing",
                0.95,
                ["release"],
            ),
            TripwireSource::counterfactual_candidate(
                "cf_billing_only",
                "Billing recovery candidate should not match release tasks",
                0.9,
                ["billing"],
            ),
            TripwireSource::dependency_contract(
                "dep_no_tokio",
                "Forbidden async runtime dependency must not appear",
                true,
                ["release"],
            ),
            TripwireSource::high_utility_memory(
                "mem_low_signal",
                "Low confidence reminder should stay below threshold",
                0.2,
                ["release"],
            ),
        ];

        let generated = generate_tripwires_from_sources(
            "pf_fixed",
            "prepare release",
            "2026-04-30T12:00:00Z",
            &sources,
            &TripwireGenerationConfig::default(),
        );
        let repeated = generate_tripwires_from_sources(
            "pf_fixed",
            "prepare release",
            "2026-04-30T12:00:00Z",
            &sources,
            &TripwireGenerationConfig::default(),
        );

        ensure(generated.len(), 2, "eligible tripwire count")?;
        ensure(
            generated[0].source_id.clone(),
            "dep_no_tokio".to_string(),
            "critical dependency contract first",
        )?;
        ensure(
            generated[1].source_id.clone(),
            "mem_release_rule".to_string(),
            "high utility memory second",
        )?;
        ensure(
            generated[0].tripwire.id.clone(),
            repeated[0].tripwire.id.clone(),
            "stable generated id",
        )?;
        ensure(
            generated[0].tripwire.condition.clone(),
            "task_contains_any(\"release\")".to_string(),
            "condition",
        )?;
        ensure(
            generated[0].trigger_terms.clone(),
            vec!["release".to_string()],
            "generated trigger terms",
        )?;
        ensure(
            generated[0].provenance.clone(),
            vec![
                "source_kind=dependency_contract".to_string(),
                "source_id=dep_no_tokio".to_string(),
                "source_score=1.000".to_string(),
            ],
            "generated provenance",
        )
    }

    #[test]
    fn regret_entries_generate_halting_tripwires_for_harmful_regret() -> TestResult {
        let entry = LedgerRegretEntry::new(
            "reg_bad_cleanup",
            "ep_cleanup",
            "cfr_cleanup",
            "int_missing_warning",
            0.9,
            0.95,
            RegretCategory::Misinformation,
            "2026-04-30T12:00:00Z",
        );
        let source = TripwireSource::regret_entry(
            &entry,
            "Wrong cleanup guidance would have caused data loss",
            ["cleanup"],
        );
        let generated = generate_tripwires_from_sources(
            "pf_cleanup",
            "perform cleanup",
            "2026-04-30T12:00:00Z",
            &[source],
            &TripwireGenerationConfig::default(),
        );

        ensure(generated.len(), 1, "generated count")?;
        ensure(generated[0].risk_level, RiskLevel::Critical, "risk level")?;
        ensure(
            generated[0].tripwire.action,
            TripwireAction::Halt,
            "halt action",
        )?;
        ensure(
            generated[0]
                .tripwire
                .message
                .as_ref()
                .is_some_and(|message| message.contains("regret_ledger_entry")),
            true,
            "source provenance in message",
        )
    }

    #[test]
    fn claim_entries_generate_pause_tripwires_for_regressed_claims() -> TestResult {
        let claim_id = crate::models::ClaimId::from_str("claim_00000000000000000000000000")
            .map_err(|err| err.to_string())?;
        let mut claim = ClaimEntry::new(
            claim_id,
            "Release workflow remains reproducible".to_string(),
            "Release artifacts should be generated from the documented workflow".to_string(),
        );
        claim.status = ClaimStatus::Regressed;

        let source = TripwireSource::claim_entry(&claim, 0.9, ["release"]);

        ensure(source.kind, TripwireSourceKind::Claim, "kind")?;
        ensure(source.risk_level, RiskLevel::High, "risk")?;
        ensure(source.action, TripwireAction::Pause, "action")
    }

    #[test]
    fn run_preflight_counts_generated_tripwires_from_sources() -> TestResult {
        let source = TripwireSource::dependency_contract(
            "dep_forbidden_runtime",
            "Forbidden runtime dependency must not be introduced",
            true,
            ["release"],
        );
        let options = RunOptions {
            task_input: "prepare release".to_string(),
            tripwire_sources: vec![source],
            ..Default::default()
        };

        let report = run_preflight(&options).map_err(|err| err.message())?;

        ensure(report.tripwires_set, 1, "tripwires_set")?;
        ensure(report.tripwires.len(), 1, "tripwire views")?;
        ensure(
            report.ask_now_prompts.is_empty(),
            true,
            "no generated ask-now prompts",
        )?;
        ensure(report.risks_identified, 1, "risk count from evidence")?;
        ensure(
            report.tripwires[0].tripwire_type.clone(),
            TripwireType::FileChange.as_str().to_string(),
            "tripwire type",
        )?;
        ensure(
            report.tripwires[0].source_kind.clone(),
            Some("dependency_contract".to_string()),
            "tripwire source kind",
        )?;
        ensure(
            report.tripwires[0].source_id.clone(),
            Some("dep_forbidden_runtime".to_string()),
            "tripwire source id",
        )?;
        ensure(
            report.tripwires[0].source_score,
            Some(1.0),
            "tripwire source score",
        )?;
        ensure(
            report.tripwires[0].trigger_terms.clone(),
            vec!["release".to_string()],
            "tripwire trigger terms",
        )?;
        ensure(
            report.tripwires[0].provenance.clone(),
            vec![
                "source_kind=dependency_contract".to_string(),
                "source_id=dep_forbidden_runtime".to_string(),
                "source_score=1.000".to_string(),
            ],
            "tripwire provenance",
        )
    }

    #[test]
    fn run_preflight_respects_disabled_tripwire_checks() -> TestResult {
        let source = TripwireSource::dependency_contract(
            "dep_forbidden_runtime",
            "Forbidden runtime dependency must not be introduced",
            true,
            ["release"],
        );
        let options = RunOptions {
            task_input: "prepare release".to_string(),
            check_tripwires: false,
            tripwire_sources: vec![source],
            ..Default::default()
        };

        let report = run_preflight(&options).map_err(|err| err.message())?;

        ensure(report.tripwires_set, 0, "tripwires disabled")?;
        ensure(report.tripwires.is_empty(), true, "no tripwire views")
    }

    /// Regression guard for the TOCTOU bounded-read defense in
    /// `read_preflight_run_store_file_no_follow`.
    ///
    /// Pre-fix, the helper called `file.read_to_string(...)` which
    /// returns *all* bytes regardless of the upstream metadata cap
    /// at `read_preflight_run_store`. A peer process growing
    /// `.ee/preflight_runs.json` between the `symlink_metadata().len()`
    /// check and the open would defeat the cap and pin a multi-MiB
    /// allocation on every `ee preflight {run,show,close}` call. This
    /// test calls the helper directly on a CAP+1 byte file —
    /// simulating the TOCTOU growth scenario — and asserts the bounded
    /// `take(CAP + 1)` reader returns `InvalidData` instead of
    /// allocating past `PREFLIGHT_RUN_STORE_MAX_BYTES`.
    #[test]
    fn preflight_run_store_bounded_read_rejects_toctou_growth() -> Result<(), String> {
        let tempdir = tempfile::tempdir().map_err(|error| error.to_string())?;
        let store_path = tempdir.path().join("preflight_runs.json");
        let cap =
            usize::try_from(PREFLIGHT_RUN_STORE_MAX_BYTES).map_err(|error| error.to_string())?;
        // Fill with a single-byte filler so each byte is valid UTF-8
        // (so the rejection trips on the size bound, not from_utf8).
        let mut payload = Vec::with_capacity(cap + 1);
        payload.resize(cap + 1, b' ');
        std::fs::write(&store_path, &payload).map_err(|error| error.to_string())?;

        let error = read_preflight_run_store_file_no_follow(&store_path)
            .expect_err("bounded read must reject CAP+1 bytes even if metadata check is bypassed");
        ensure(
            error.kind() == std::io::ErrorKind::InvalidData,
            true,
            "bounded read TOCTOU rejection must surface InvalidData",
        )?;
        let message = error.to_string();
        ensure(
            message.contains("TOCTOU"),
            true,
            "rejection message must name the TOCTOU defense",
        )?;
        ensure(
            message.contains(&PREFLIGHT_RUN_STORE_MAX_BYTES.to_string()),
            true,
            "rejection message must cite the cap constant",
        )
    }
}