areev-loop 1.8.3

Areev Loop: the governed self-improvement engine for AI-agent memory. Standalone engine over an OmsSubstrate (CAL + grains) — zero Areev dependencies.
Documentation
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
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
//! Engine end-to-end tests over the reference substrate: the full
//! propose → review → apply → rollback loop, gating, dedup idempotency, the
//! destructive gate, scopes, and the self-approval block. Compiled only under
//! `cfg(test)`.

use crate::engine::{Decision, Engine, RunOptions, RunOutcome, Scope, ScopeSet, SkipReason, LOOP_NS};
use crate::error::Error;
use crate::policy::Policy;
use crate::recommendation::{ObserverType, RecStatus, Recommendation};
use crate::testkit::TestSubstrate;

struct CountingSubstrate<'a> {
    inner: &'a mut crate::reference::ReferenceSubstrate,
    effect_calls: usize,
    unpinned_specs: usize,
}

impl CountingSubstrate<'_> {
    fn note_spec(&mut self, spec: &crate::substrate::GrainSpec) {
        self.effect_calls += 1;
        if !spec.fields.contains_key("created_at_ms") && !spec.fields.contains_key("at_ms") {
            self.unpinned_specs += 1;
        }
    }
}

impl crate::substrate::SubstrateRead for CountingSubstrate<'_> {
    fn capabilities(&self) -> crate::substrate::Capabilities {
        self.inner.capabilities()
    }

    fn grains_of_type(
        &self,
        grain_type: &str,
        namespace: Option<&str>,
        opts: crate::substrate::ReadOpts,
    ) -> crate::error::Result<Vec<crate::model::GrainRecord>> {
        self.inner.grains_of_type(grain_type, namespace, opts)
    }

    fn grain(&self, hash: &str) -> crate::error::Result<Option<crate::model::GrainRecord>> {
        self.inner.grain(hash)
    }

    fn heads(
        &self,
        namespace: Option<&str>,
    ) -> crate::error::Result<Vec<crate::substrate::HeadGroup>> {
        self.inner.heads(namespace)
    }

    fn telemetry(
        &self,
        namespace: Option<&str>,
    ) -> crate::error::Result<Option<crate::substrate::TelemetryView>> {
        self.inner.telemetry(namespace)
    }
}

impl crate::substrate::OmsSubstrate for CountingSubstrate<'_> {
    fn put_grain(
        &mut self,
        spec: &crate::substrate::GrainSpec,
    ) -> crate::error::Result<String> {
        self.note_spec(spec);
        self.inner.put_grain(spec)
    }

    fn supersede(
        &mut self,
        target_hash: &str,
        spec: &crate::substrate::GrainSpec,
        justification: &str,
    ) -> crate::error::Result<String> {
        self.note_spec(spec);
        self.inner.supersede(target_hash, spec, justification)
    }

    fn retract(&mut self, hash: &str, reason: &str) -> crate::error::Result<()> {
        self.effect_calls += 1;
        self.inner.retract(hash, reason)
    }

    fn execute_cal(&mut self, cal: &str) -> crate::error::Result<Vec<serde_json::Value>> {
        self.effect_calls += 1;
        self.inner.execute_cal(cal)
    }

    fn validate_cal(&self, cal: &str) -> crate::error::Result<()> {
        self.inner.validate_cal(cal)
    }

    fn load_state(&self) -> crate::error::Result<serde_json::Value> {
        self.inner.load_state()
    }

    fn store_state(&mut self, state: &serde_json::Value) -> crate::error::Result<()> {
        self.effect_calls += 1;
        self.inner.store_state(state)
    }
}

fn seed_all(sub: &mut TestSubstrate) {
    // exact-duplicate facts
    sub.add_fact("acme", "tier", "Enterprise");
    sub.add_fact("acme", "tier", "Enterprise");
    // contradiction under a functional relation
    sub.add_fact("acme", "deploy_target", "us-east-1");
    sub.add_fact("acme", "deploy_target", "eu-west-1");
    // an expired grain
    sub.add_fact_valid_to("promo", "active", "true", 500);
    // a dominant tool-failure cluster
    for _ in 0..5 {
        sub.add_tool_call("stripe_refund", true, "rate_limited 429");
    }
    sub.add_tool_call("stripe_refund", false, "ok");
}

#[test]
fn run_proposes_across_analyzers_and_is_idempotent() {
    let mut sub = TestSubstrate::new();
    seed_all(&mut sub);
    let e = Engine::with_builtins();

    let r1 = e
        .run(&mut sub.inner, &RunOptions::default(), 10_000)
        .unwrap();
    assert!(r1.ran());
    assert!(
        r1.stored >= 4,
        "expected duplicate + contradiction + staleness + tool-failure, got {}",
        r1.stored
    );

    // Same findings on a second run collapse to nothing new (dedup).
    let r2 = e
        .run(&mut sub.inner, &RunOptions::default(), 20_000)
        .unwrap();
    assert!(r2.ran());
    assert_eq!(r2.stored, 0, "no re-proposals");
}

#[test]
fn analyze_only_is_side_effect_free_and_matches_production_decisions() {
    use crate::substrate::{OmsSubstrate, ReadOpts, SubstrateRead};
    use std::collections::BTreeMap;

    let mut sub = TestSubstrate::new();
    seed_all(&mut sub);
    let e = Engine::with_builtins();
    let opts = RunOptions::default();
    let now = 10_000;
    let mut counted = CountingSubstrate {
        inner: &mut sub.inner,
        effect_calls: 0,
        unpinned_specs: 0,
    };
    let state_before = counted.load_state().unwrap();
    let count_before: usize = [
        "fact",
        "event",
        "tool",
        "observation",
        "recommendation",
        "audit",
    ]
    .iter()
    .map(|ty| {
        counted
            .grains_of_type(
                ty,
                None,
                ReadOpts {
                    live_only: false,
                    since_ms: None,
                },
            )
            .unwrap()
            .len()
    })
    .sum();

    let replay = e
        .analyze_only(&counted, &opts, &BTreeMap::new(), now)
        .unwrap();
    assert_eq!(counted.effect_calls, 0, "replay must invoke no effect executor");
    assert_eq!(counted.load_state().unwrap(), state_before, "state is immutable");
    let count_after: usize = [
        "fact",
        "event",
        "tool",
        "observation",
        "recommendation",
        "audit",
    ]
    .iter()
    .map(|ty| {
        counted
            .grains_of_type(
                ty,
                None,
                ReadOpts {
                    live_only: false,
                    since_ms: None,
                },
            )
            .unwrap()
            .len()
    })
    .sum();
    assert_eq!(count_after, count_before, "analysis must append no grains or audit rows");

    e.run(&mut counted, &opts, now).unwrap();
    assert!(counted.effect_calls > 0, "production control must exercise effects");
    assert_eq!(counted.unpinned_specs, 0, "engine writes must carry an injected clock");
    let stored = counted
        .grains_of_type(
            crate::model::grain_type::RECOMMENDATION,
            Some(LOOP_NS),
            ReadOpts {
                live_only: false,
                since_ms: None,
            },
        )
        .unwrap()
        .into_iter()
        .map(|g| Recommendation::from_fields(&g.hash, &g.fields).unwrap())
        .collect::<Vec<_>>();
    let replay_values: Vec<_> = replay
        .iter()
        .map(|r| serde_json::to_value(r).unwrap())
        .collect();
    let stored_values: Vec<_> = stored
        .iter()
        .map(|r| serde_json::to_value(r).unwrap())
        .collect();
    assert_eq!(replay_values, stored_values, "replay preserves production decision order");
}

#[test]
fn analyze_only_overrides_are_validated_and_applied() {
    use std::collections::BTreeMap;

    let mut sub = TestSubstrate::new();
    for _ in 0..5 {
        sub.add_tool_call("stripe_refund", true, "rate_limited 429");
    }
    let e = Engine::with_builtins();
    let baseline = e
        .analyze_only(&sub.inner, &RunOptions::default(), &BTreeMap::new(), 10_000)
        .unwrap();
    assert!(baseline.iter().any(|r| r.analyzer.starts_with("loop.tool_failure")));

    let mut params = serde_json::Map::new();
    params.insert("min_count".into(), serde_json::json!(10));
    let overrides = BTreeMap::from([("loop.tool_failure/1".to_string(), params)]);
    let replay = e
        .analyze_only(&sub.inner, &RunOptions::default(), &overrides, 10_000)
        .unwrap();
    assert!(replay.iter().all(|r| !r.analyzer.starts_with("loop.tool_failure")));
}

/// A canned LLM backend keyed by op (discover / ground / verify / enrich) so a
/// test can drive the whole PROPOSE → GROUND → VERIFY → ENRICH pipeline.
struct MockLlm {
    discover: String,
    ground: String,
    verify: String,
    enrich: String,
}
impl crate::llm::LlmBackend for MockLlm {
    fn model(&self) -> &str {
        "mock-llm"
    }
    fn complete(&self, request: &str) -> crate::error::Result<String> {
        Ok(if request.contains("\"op\":\"discover\"") {
            self.discover.clone()
        } else if request.contains("\"op\":\"ground\"") {
            self.ground.clone()
        } else if request.contains("\"op\":\"verify\"") {
            self.verify.clone()
        } else {
            self.enrich.clone()
        })
    }
}

/// A draft may cite bundled evidence by the short id the bundle labels it
/// with, not only by the full hash — and a citation naming nothing in the
/// bundle is still a fabrication that drops the draft.
#[test]
fn llm_drafts_may_cite_evidence_by_bundle_id() {
    use crate::model::Origin;
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("acme", "deploy_target", "us-east-1");
    let h2 = sub.add_fact("acme", "deploy_target", "eu-west-1");
    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"by id","target":"entity:test/acme","evidence":["e1"],"confidence":0.9}},
          {{"summary":"by hash","target":"grain:{h2}","evidence":["{h2}"],"confidence":0.9}},
          {{"summary":"fabricated","target":"entity:test/acme","evidence":["e99","not-a-hash"],"confidence":0.9}}
        ]}}"#
    );
    let e = Engine::with_builtins().with_llm(Box::new(MockLlm {
        discover,
        ground: r#"{"results":[{"id":0,"supported":true,"reason":"ok"},{"id":1,"supported":true,"reason":"ok"}]}"#.into(),
        verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9,"reason":"ok"},{"id":1,"keep":true,"confidence":0.9,"reason":"ok"}]}"#.into(),
        enrich: r#"{"notes":[]}"#.into(),
    }));
    let out = e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let funnel = out.llm_funnel.expect("an llm run reports its funnel");
    assert_eq!(funnel.proposed, 3);
    assert_eq!(funnel.dropped_uncited, 1, "the fabricated citation is the only drop");
    let llm: Vec<Recommendation> = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .filter(|r| matches!(r.origin, Origin::Llm { .. }))
        .collect();
    // Distinct targets, so dedup (family ⟂ target ⟂ action) keeps both.
    assert_eq!(llm.len(), 2, "id- and hash-cited drafts both survive");
    for r in &llm {
        assert!(
            r.evidence.iter().all(|h| h == &h1 || h == &h2),
            "stored evidence is the resolved grain hash, never the label: {:?}",
            r.evidence
        );
    }
    assert!(llm.iter().all(|r| r.summary.render() != "fabricated"));
}

/// The three citation shapes, pinned on the resolver itself (the reference
/// substrate's hashes are not hex, so the prefix rule needs a direct test).
#[test]
fn citation_resolves_by_hash_id_or_unambiguous_hex_prefix() {
    use crate::engine::resolve_citation;
    use std::collections::{BTreeMap, BTreeSet};
    let a = "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90".to_string();
    let b = "a1b2c3d4e5f6ffffffffffffffffffffffffffffffffffffffffffffffffffff".to_string();
    let bundle: BTreeSet<String> = [a.clone(), b.clone()].into_iter().collect();
    let ids: BTreeMap<&str, &str> = [("e1", a.as_str()), ("e2", b.as_str())].into_iter().collect();
    assert_eq!(resolve_citation(&a, &bundle, &ids).as_deref(), Some(a.as_str()));
    assert_eq!(resolve_citation("e2", &bundle, &ids).as_deref(), Some(b.as_str()));
    assert_eq!(resolve_citation(" e1 ", &bundle, &ids).as_deref(), Some(a.as_str()), "whitespace-tolerant");
    assert_eq!(resolve_citation(&a[..16], &bundle, &ids).as_deref(), Some(a.as_str()), "unambiguous prefix");
    assert_eq!(resolve_citation(&a[..16].to_uppercase(), &bundle, &ids).as_deref(), Some(a.as_str()));
    assert_eq!(resolve_citation(&a[..12], &bundle, &ids), None, "shared 12-char prefix is ambiguous");
    assert_eq!(resolve_citation(&a[..8], &bundle, &ids), None, "too short to count as a citation");
    assert_eq!(resolve_citation("e3", &bundle, &ids), None);
    assert_eq!(resolve_citation("", &bundle, &ids), None);
}

/// Two lessons on one entity that both regress get TWO reverts. A revert's
/// dedup key includes the hash of what it reverts; keyed by target alone,
/// the second was dropped as a duplicate of the first (the learning-curve
/// study's seed 3: two regressed, one revert proposed).
#[test]
fn two_regressed_lessons_on_one_target_get_two_reverts() {
    use crate::model::Origin;
    let t = 5_000_000;
    let scopes = ScopeSet::all();
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("capture", "correction", "vendor missing");
    let journal = |sub: &mut TestSubstrate, run_id: &str, exact: u64, at: i64| {
        sub.add_fact_at(
            "agent:harness",
            "evalset:heldout1",
            "mg:eval_run",
            &format!(r#"{{"run_id":"{run_id}","passed":{exact},"failed":{},"exact":{exact}}}"#, 100 - exact),
            at,
        );
    };
    journal(&mut sub, "eval-before", 90, t - DAY);
    let llm = MockLlm {
        discover: format!(
            r#"{{"recommendations":[{{"summary":"dates as printed","target":"entity:test/capture","evidence":["{h1}"],"confidence":0.9,"proposal":{{"kind":"lesson","lesson":"Copy the file date exactly as printed."}}}},{{"summary":"names as printed","target":"entity:test/capture","evidence":["{h1}"],"confidence":0.9,"proposal":{{"kind":"lesson","lesson":"Copy the signer name exactly as printed."}}}}]}}"#
        ),
        ground: r#"{"results":[{"id":0,"supported":true,"reason":"ok"},{"id":1,"supported":true,"reason":"ok"}]}"#.into(),
        verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9,"reason":"ok"},{"id":1,"keep":true,"confidence":0.9,"reason":"ok"}]}"#.into(),
        enrich: r#"{"notes":[]}"#.into(),
    };
    let policy = Policy::from_json(
        r#"{"outcome_evalset": {"hash": "heldout1", "field": "exact", "higher_is_better": true}}"#,
    )
    .unwrap();
    let e = Engine::with_builtins().with_llm(Box::new(llm)).with_policy(policy);
    e.run(&mut sub.inner, &RunOptions::default(), t).unwrap();
    let lessons: Vec<Recommendation> = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .filter(|r| matches!(r.origin, Origin::Llm { .. }))
        .collect();
    assert_eq!(lessons.len(), 2, "two different lessons on one entity both reach the queue");
    for (i, r) in lessons.iter().enumerate() {
        e.review(&mut sub.inner, &r.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "ok", t + 1 + i as i64)
            .unwrap();
        e.apply(&mut sub.inner, &r.hash, "user:a", ObserverType::Human, &scopes, "apply", false, t + 10 + i as i64)
            .unwrap();
    }
    journal(&mut sub, "eval-after", 60, t + DAY + 100);
    e.run(&mut sub.inner, &RunOptions::default(), t + DAY + 200).unwrap();
    let regressed: Vec<_> = e
        .outcomes(&sub.inner)
        .unwrap()
        .into_iter()
        .filter(|o| o.verdict == "regressed")
        .collect();
    assert_eq!(regressed.len(), 2, "both lessons measured regressed");
    let reverts: Vec<Recommendation> = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .filter(|r| r.analyzer.starts_with("loop.outcome_review"))
        .collect();
    assert_eq!(reverts.len(), 2, "one revert per regressed lesson, not one per target");
    let mut keys: Vec<_> = reverts.iter().map(|r| r.dedup_key.clone()).collect();
    keys.dedup();
    assert_eq!(keys.len(), 2, "distinct dedup keys");
}

/// A verdict compares against the state of the world at the APPLY, not at the
/// proposal. A deployment that journals its evalset once, on day one, and
/// then approves rule after rule would otherwise measure its twentieth rule
/// against day one — and a rule that cost twenty points reads as `held`
/// against a baseline the first nineteen rules had long since left behind.
/// Found on a real corpus (`crates/areev-bench/CURVE.md`, seed 1: 86% → 66%,
/// measured as held against 26%). With nothing journaled between the
/// proposal and the apply, the baseline is the proposal's own run, so the
/// test right below this one is unchanged.
#[test]
fn a_run_journaled_before_the_apply_is_the_lessons_baseline() {
    use crate::model::Origin;
    let t = 5_000_000;
    let scopes = ScopeSet::all();
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("capture", "correction", "vendor missing");
    let journal = |sub: &mut TestSubstrate, run_id: &str, exact: u64, at: i64| {
        sub.add_fact_at(
            "agent:harness",
            "evalset:heldout1",
            "mg:eval_run",
            &format!(r#"{{"run_id":"{run_id}","passed":{exact},"failed":{},"exact":{exact}}}"#, 100 - exact),
            at,
        );
    };
    // Day one: 26 of 100. Then the deployment's earlier rules take it to 86.
    journal(&mut sub, "eval-day-one", 26, t - 3 * DAY);
    let llm = MockLlm {
        discover: format!(
            r#"{{"recommendations":[{{"summary":"dates are being standardised","target":"entity:test/capture","evidence":["{h1}"],"confidence":0.9,"proposal":{{"kind":"lesson","lesson":"Copy the file date exactly as printed, in its original format."}}}}]}}"#
        ),
        ground: r#"{"results":[{"id":0,"supported":true,"reason":"ok"}]}"#.into(),
        verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9,"reason":"ok"}]}"#.into(),
        enrich: r#"{"notes":[]}"#.into(),
    };
    let policy = Policy::from_json(
        r#"{"outcome_evalset": {"hash": "heldout1", "field": "exact", "higher_is_better": true}}"#,
    )
    .unwrap();
    let e = Engine::with_builtins().with_llm(Box::new(llm)).with_policy(policy);
    e.run(&mut sub.inner, &RunOptions::default(), t).unwrap();
    let rec = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }))
        .expect("the lesson is proposed");
    assert_eq!(rec.metric.as_ref().unwrap().baseline, 26.0, "the proposal froze day one");
    // Measured again before the apply: 86. THIS is what the rule is judged against.
    journal(&mut sub, "eval-before-apply", 86, t + 1);
    e.review(&mut sub.inner, &rec.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "reads fine", t + 2)
        .unwrap();
    e.apply(&mut sub.inner, &rec.hash, "user:a", ObserverType::Human, &scopes, "apply the lesson", false, t + 3)
        .unwrap();
    // After the apply: 66. Better than day one; twenty points worse than the apply.
    // (The 1d checkpoint is due a day after the apply at t + 3.)
    journal(&mut sub, "eval-after", 66, t + DAY + 10);
    e.run(&mut sub.inner, &RunOptions::default(), t + DAY + 20).unwrap();
    let verdicts: Vec<_> = e
        .outcomes(&sub.inner)
        .unwrap()
        .into_iter()
        .filter(|o| o.rec_hash == rec.hash)
        .collect();
    assert_eq!(verdicts.len(), 1);
    assert_eq!(
        (verdicts[0].baseline, verdicts[0].current, verdicts[0].verdict.as_str()),
        (86.0, 66.0, "regressed"),
        "judged against the run before the apply, not the day-one snapshot"
    );
    assert!(
        e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .iter()
            .any(|r| r.analyzer.starts_with("loop.outcome_review")),
        "and the revert is proposed"
    );
}

/// An LLM-authored lesson carries no recurrence metric — nothing errors when
/// a lesson is merely useless — so `Policy::outcome_evalset` gives every
/// applicable authored proposal the host's evalset as its metric: baseline
/// from the newest run journaled before the proposal, current from runs
/// journaled after the apply. A worse run after the apply is a regression,
/// the gate proposes the revert, applying it retracts the lesson and puts it
/// on cooldown. Without a baseline run there is no metric at all.
#[test]
fn an_authored_lesson_is_measured_against_the_policy_evalset_and_reverted_on_regression() {
    use crate::model::Origin;
    use crate::substrate::OmsSubstrate;
    let t = 5_000_000;
    let scopes = ScopeSet::all();
    let lesson_llm = |h1: &str| MockLlm {
        discover: format!(
            r#"{{"recommendations":[{{"summary":"the agent keeps skipping the vendor","target":"entity:test/capture","evidence":["{h1}"],"confidence":0.9,"proposal":{{"kind":"lesson","lesson":"Record the vendor name on every receipt."}}}}]}}"#
        ),
        ground: r#"{"results":[{"id":0,"supported":true,"reason":"ok"}]}"#.into(),
        verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9,"reason":"ok"}]}"#.into(),
        enrich: r#"{"notes":[]}"#.into(),
    };
    let policy = || {
        Policy::from_json(
            r#"{"outcome_evalset": {"hash": "heldout1", "field": "exact", "higher_is_better": true}}"#,
        )
        .unwrap()
    };
    let journal = |sub: &mut TestSubstrate, run_id: &str, exact: u64, at: i64| {
        sub.add_fact_at(
            "agent:harness",
            "evalset:heldout1",
            "mg:eval_run",
            &format!(r#"{{"run_id":"{run_id}","passed":{exact},"failed":{},"exact":{exact}}}"#, 60 - exact),
            at,
        );
    };
    let llm_pending = |e: &Engine, sub: &TestSubstrate| -> Vec<Recommendation> {
        e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .into_iter()
            .filter(|r| matches!(r.origin, Origin::Llm { .. }))
            .collect()
    };

    // No baseline run journaled → the lesson is stored without a metric.
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("capture", "correction", "vendor missing");
    let e = Engine::with_builtins().with_llm(Box::new(lesson_llm(&h1))).with_policy(policy());
    e.run(&mut sub.inner, &RunOptions::default(), t).unwrap();
    let recs = llm_pending(&e, &sub);
    assert_eq!(recs.len(), 1);
    assert!(recs[0].metric.is_none(), "no journaled run → honestly unmeasured");

    // With a baseline run: the metric names the evalset and carries its value.
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("capture", "correction", "vendor missing");
    journal(&mut sub, "eval-baseline", 20, t - 3_600_000);
    let e = Engine::with_builtins().with_llm(Box::new(lesson_llm(&h1))).with_policy(policy());
    e.run(&mut sub.inner, &RunOptions::default(), t).unwrap();
    let recs = llm_pending(&e, &sub);
    assert_eq!(recs.len(), 1);
    let m = recs[0].metric.as_ref().expect("an applicable authored lesson carries the evalset metric");
    assert_eq!(m.metric, "evalset:heldout1:exact");
    assert_eq!(m.baseline, 20.0);
    assert!(m.higher_is_better);
    assert_eq!(m.horizons_ms, vec![DAY, 7 * DAY, 30 * DAY]);
    let hash = recs[0].hash.clone();
    let dk = recs[0].dedup_key.clone();

    e.review(&mut sub.inner, &hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "try it", t + 1)
        .unwrap();
    e.apply(&mut sub.inner, &hash, "user:a", ObserverType::Human, &scopes, "apply the lesson", false, t + 2)
        .unwrap();

    // A run journaled BEFORE the apply is not evidence: with none after it,
    // the 1d checkpoint stays due and no verdict is recorded.
    e.run(&mut sub.inner, &RunOptions::default(), t + 2 * DAY).unwrap();
    assert!(
        e.outcomes(&sub.inner).unwrap().iter().all(|o| o.rec_hash != hash),
        "no run since the apply → not yet measurable, never scored against the baseline"
    );

    // A worse run after the apply → regressed at the 1d checkpoint → revert.
    journal(&mut sub, "eval-after", 12, t + 2 * DAY + 1);
    e.run(&mut sub.inner, &RunOptions::default(), t + 2 * DAY + 2).unwrap();
    let verdicts: Vec<_> = e
        .outcomes(&sub.inner)
        .unwrap()
        .into_iter()
        .filter(|o| o.rec_hash == hash)
        .collect();
    assert_eq!(verdicts.len(), 1);
    assert_eq!((verdicts[0].baseline, verdicts[0].current, verdicts[0].verdict.as_str()), (20.0, 12.0, "regressed"));
    let revert = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| r.analyzer.starts_with("loop.outcome_review"))
        .expect("the regression proposed a revert");
    e.review(&mut sub.inner, &revert.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "it hurt", t + 2 * DAY + 3)
        .unwrap();
    e.apply(&mut sub.inner, &revert.hash, "user:a", ObserverType::Human, &scopes, "revert", false, t + 2 * DAY + 4)
        .unwrap();
    assert_eq!(status_of(&e, &sub, &hash), RecStatus::RolledBack);
    let cooled = crate::config::LoopPersisted::from_value(sub.inner.load_state().unwrap())
        .unwrap()
        .cooldowns
        .get(&dk)
        .copied();
    assert_eq!(cooled, Some(t + 2 * DAY + 4 + 7 * DAY), "the reverted lesson is on cooldown");

    // The same evidence, the same model, the next pass: not re-proposed.
    e.run(&mut sub.inner, &RunOptions::default(), t + 2 * DAY + 5).unwrap();
    assert!(
        llm_pending(&e, &sub).iter().all(|r| r.dedup_key != dk),
        "a lesson the gate just retracted is not re-proposed on the next pass"
    );

    // A better run after the apply → held.
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("capture", "correction", "vendor missing");
    journal(&mut sub, "eval-baseline", 20, t - 3_600_000);
    let e = Engine::with_builtins().with_llm(Box::new(lesson_llm(&h1))).with_policy(policy());
    e.run(&mut sub.inner, &RunOptions::default(), t).unwrap();
    let hash = llm_pending(&e, &sub)[0].hash.clone();
    e.review(&mut sub.inner, &hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "try it", t + 1)
        .unwrap();
    e.apply(&mut sub.inner, &hash, "user:a", ObserverType::Human, &scopes, "apply", false, t + 2)
        .unwrap();
    journal(&mut sub, "eval-after", 33, t + 3);
    // The 1d checkpoint is due one day after the APPLY (t + 2), not after t.
    e.run(&mut sub.inner, &RunOptions::default(), t + 2 + DAY).unwrap();
    let verdicts: Vec<_> = e.outcomes(&sub.inner).unwrap().into_iter().filter(|o| o.rec_hash == hash).collect();
    assert_eq!(verdicts.len(), 1);
    assert_eq!(verdicts[0].verdict, "held");
    assert!(
        !e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .iter()
            .any(|r| r.analyzer.starts_with("loop.outcome_review")),
        "an improvement proposes no revert"
    );
}

/// Two different authored lessons on ONE entity are two findings — both
/// reach the queue, and the second is not a duplicate of the first even
/// while the first is applied. The same lesson re-authored (at a different
/// confidence, with different spacing) IS a duplicate. An advisory flag
/// keeps the analyzer-style key: one open flag per target.
#[test]
fn authored_lessons_dedup_on_content_not_only_on_target() {
    use crate::model::Origin;
    let scopes = ScopeSet::all();
    let llm = |h1: &str, lessons: &[&str]| {
        let recs: Vec<String> = lessons
            .iter()
            .map(|l| format!(
                r#"{{"summary":"{l}","target":"entity:test/capture","evidence":["{h1}"],"confidence":0.9,"proposal":{{"kind":"lesson","lesson":"{l}"}}}}"#
            ))
            .collect();
        let n = lessons.len();
        MockLlm {
            discover: format!(r#"{{"recommendations":[{}]}}"#, recs.join(",")),
            ground: format!(
                r#"{{"results":[{}]}}"#,
                (0..n).map(|i| format!(r#"{{"id":{i},"supported":true,"reason":"ok"}}"#)).collect::<Vec<_>>().join(",")
            ),
            verify: format!(
                r#"{{"results":[{}]}}"#,
                (0..n).map(|i| format!(r#"{{"id":{i},"keep":true,"confidence":0.9,"reason":"ok"}}"#)).collect::<Vec<_>>().join(",")
            ),
            enrich: r#"{"notes":[]}"#.into(),
        }
    };
    let llm_recs = |e: &Engine, sub: &TestSubstrate, status: Option<RecStatus>| -> Vec<Recommendation> {
        e.recommendations(&sub.inner, status)
            .unwrap()
            .into_iter()
            .filter(|r| matches!(r.origin, Origin::Llm { .. }))
            .collect()
    };

    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("capture", "correction", "vendor and amount missing");
    let e = Engine::with_builtins().with_llm(Box::new(llm(
        &h1,
        &["Record the vendor name on every receipt.", "Record the amount on every receipt."],
    )));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = llm_recs(&e, &sub, Some(RecStatus::Pending));
    assert_eq!(recs.len(), 2, "two different lessons on one entity both reach the queue");
    assert_ne!(recs[0].dedup_key, recs[1].dedup_key);
    let vendor = recs.iter().find(|r| r.summary.render().contains("vendor")).unwrap().clone();
    e.review(&mut sub.inner, &vendor.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "yes", 10_001)
        .unwrap();
    e.apply(&mut sub.inner, &vendor.hash, "user:a", ObserverType::Human, &scopes, "apply", false, 10_002)
        .unwrap();

    // The vendor lesson again (reworded only in spacing/case) plus a THIRD
    // lesson: the repeat is deduped against the applied one, the new one is
    // admitted.
    let e = Engine::with_builtins().with_llm(Box::new(llm(
        &h1,
        &["record  the VENDOR name on every receipt", "Copy the address exactly as printed."],
    )));
    sub.add_fact("capture", "correction", "address missing");
    // A full sweep, so the bundle holds the evidence the drafts cite
    // regardless of the first pass's watermark.
    let sweep = RunOptions { full_sweep: true, ..RunOptions::default() };
    e.run(&mut sub.inner, &sweep, 20_000).unwrap();
    let all = llm_recs(&e, &sub, None);
    assert_eq!(all.len(), 3, "vendor (applied), amount (pending), address (pending) — the repeat was deduped");
    let pending = llm_recs(&e, &sub, Some(RecStatus::Pending));
    assert_eq!(pending.len(), 2);
    assert!(pending.iter().any(|r| r.summary.render().contains("address")));
    assert!(
        !pending.iter().any(|r| r.summary.render().to_lowercase().contains("vendor")),
        "the applied lesson is not re-queued under a cosmetic rewording"
    );

    // Advisory drafts (no proposal) on one target still collapse to one.
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("capture", "correction", "x");
    let e = Engine::with_builtins().with_llm(Box::new(MockLlm {
        discover: format!(
            r#"{{"recommendations":[
              {{"summary":"look at this","target":"entity:test/capture","evidence":["{h1}"],"confidence":0.9}},
              {{"summary":"and at this","target":"entity:test/capture","evidence":["{h1}"],"confidence":0.9}}
            ]}}"#
        ),
        ground: r#"{"results":[{"id":0,"supported":true},{"id":1,"supported":true}]}"#.into(),
        verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9},{"id":1,"keep":true,"confidence":0.9}]}"#.into(),
        enrich: r#"{"notes":[]}"#.into(),
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    assert_eq!(llm_recs(&e, &sub, Some(RecStatus::Pending)).len(), 1, "one open advisory flag per target");
}

/// An Observation reaches the model with its observer named. A bare
/// sentence is ambiguous about direction in the way that matters: a
/// person's correction reads identically to the agent being told something
/// it asked for, and a model given unattributed corrections concluded the
/// agent had been doing the asking. A Fact still renders as its triple, and
/// an Observation with no recorded observer still renders as its bare text.
#[test]
fn an_observation_reaches_the_model_with_its_observer_named() {
    use std::sync::{Arc, Mutex};
    struct Capturing(Arc<Mutex<Vec<String>>>);
    impl crate::llm::LlmBackend for Capturing {
        fn model(&self) -> &str {
            "capture"
        }
        fn complete(&self, request: &str) -> crate::error::Result<String> {
            self.0.lock().unwrap().push(request.to_string());
            Ok(r#"{"recommendations":[]}"#.into())
        }
    }
    let mut sub = TestSubstrate::new();
    sub.add_fact("acme", "deploy_target", "us-east-1");
    sub.add_fact("acme", "deploy_target", "eu-west-1");
    sub.add_human_note("test", "capture", "user:accountant", "Vendor Name is ACME LTD.");
    sub.add_observation("test", "an unattributed note");

    let seen = Arc::new(Mutex::new(Vec::new()));
    let e = Engine::with_builtins().with_llm(Box::new(Capturing(seen.clone())));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let reqs = seen.lock().unwrap();
    let req = reqs
        .iter()
        .find(|r| r.contains("\"op\":\"discover\""))
        .expect("a discover call was made");
    let v: serde_json::Value = serde_json::from_str(req).unwrap();
    let texts: Vec<String> = v["evidence"]
        .as_array()
        .unwrap()
        .iter()
        .map(|e| e["text"].as_str().unwrap_or("").to_string())
        .collect();
    assert!(
        texts.iter().any(|t| t == "user:accountant (a person) said of capture: Vendor Name is ACME LTD."),
        "a human observation names its observer: {texts:?}"
    );
    assert!(
        texts.iter().any(|t| t == "an unattributed note"),
        "an observation with no observer still renders as its bare text: {texts:?}"
    );
    assert!(
        texts.iter().any(|t| t == "acme deploy_target us-east-1"),
        "a fact still renders as its triple: {texts:?}"
    );
}

/// `evidence_attribution: anonymous` restores the pre-2026-09-04 projection
/// exactly — the bare text, no observer. It is host policy because an
/// observer id can be a person's name, and because it is the one variable
/// the receipts ablation turns.
#[test]
fn attribution_can_be_turned_off_by_host_policy() {
    use std::sync::{Arc, Mutex};
    struct Capturing(Arc<Mutex<Vec<String>>>);
    impl crate::llm::LlmBackend for Capturing {
        fn model(&self) -> &str {
            "capture"
        }
        fn complete(&self, request: &str) -> crate::error::Result<String> {
            self.0.lock().unwrap().push(request.to_string());
            Ok(r#"{"recommendations":[]}"#.into())
        }
    }
    let texts_under = |policy: Option<Policy>| -> Vec<String> {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let mut sub = TestSubstrate::new();
        sub.add_fact("acme", "deploy_target", "us-east-1");
        sub.add_fact("acme", "deploy_target", "eu-west-1");
        sub.add_human_note("test", "capture", "user:accountant", "Vendor Name is ACME LTD.");
        let mut e = Engine::with_builtins().with_llm(Box::new(Capturing(seen.clone())));
        if let Some(p) = policy {
            e = e.with_policy(p);
        }
        e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
        let reqs = seen.lock().unwrap();
        let req = reqs
            .iter()
            .find(|r| r.contains(r#""op":"discover""#))
            .expect("a discover call");
        serde_json::from_str::<serde_json::Value>(req).unwrap()["evidence"]
            .as_array()
            .unwrap()
            .iter()
            .map(|e| e["text"].as_str().unwrap_or("").to_string())
            .collect()
    };
    let named = texts_under(None);
    let anon = texts_under(Some(
        Policy::from_json(r#"{"evidence_attribution": "anonymous"}"#).unwrap(),
    ));
    assert!(named.iter().any(|t| t.contains("user:accountant (a person) said")), "{named:?}");
    assert!(anon.iter().any(|t| t == "Vendor Name is ACME LTD."), "{anon:?}");
    assert!(!anon.iter().any(|t| t.contains("(a person) said")),
            "anonymous attributes nothing: {anon:?}");
    // Only the observation's rendering changes; facts are untouched.
    let facts = |v: &Vec<String>| -> Vec<String> {
        v.iter().filter(|t| t.starts_with("acme ")).cloned().collect()
    };
    assert_eq!(facts(&named), facts(&anon));
}

/// The DISCOVER objective is host policy: the default keeps the review-queue
/// rule byte-for-byte, and `learner` swaps exactly the scoring paragraph.
#[test]
fn discover_objective_is_selected_by_host_policy() {
    use std::sync::{Arc, Mutex};
    struct Capturing(Arc<Mutex<Vec<String>>>);
    impl crate::llm::LlmBackend for Capturing {
        fn model(&self) -> &str {
            "capture"
        }
        fn complete(&self, request: &str) -> crate::error::Result<String> {
            self.0.lock().unwrap().push(request.to_string());
            Ok(r#"{"recommendations":[]}"#.into())
        }
    }
    let discover_instructions = |policy: Option<Policy>| -> String {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let mut sub = TestSubstrate::new();
        sub.add_fact("acme", "deploy_target", "us-east-1");
        sub.add_fact("acme", "deploy_target", "eu-west-1");
        let mut e = Engine::with_builtins().with_llm(Box::new(Capturing(seen.clone())));
        if let Some(p) = policy {
            e = e.with_policy(p);
        }
        e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
        let reqs = seen.lock().unwrap();
        let req = reqs
            .iter()
            .find(|r| r.contains("\"op\":\"discover\""))
            .expect("a discover call was made");
        serde_json::from_str::<serde_json::Value>(req).unwrap()["instructions"]
            .as_str()
            .unwrap()
            .to_string()
    };
    let default = discover_instructions(None);
    let learner = discover_instructions(Some(
        Policy::from_json(r#"{"discover_objective": "learner"}"#).unwrap(),
    ));
    assert!(default.contains("returning nothing earns 0"), "review-queue rule by default");
    assert!(!default.contains("learning stage"));
    assert!(learner.contains("learning stage of a deployed agent"));
    assert!(learner.contains("ALSO penalized"));
    assert!(!learner.contains("returning nothing earns 0"));
    // Everything but the scoring paragraph is shared verbatim.
    for shared in [
        "propose ADDITIONAL findings",
        "Require at least two rejected outcomes",
        "MUST cite one or more evidence items from the bundle by their 'id'",
        "\"kind\":\"lesson\"",
        "Propose nothing you cannot ground in the evidence.",
    ] {
        assert!(default.contains(shared) && learner.contains(shared), "{shared}");
    }
}

#[test]
fn llm_discover_verified_rec_is_stamped_with_confidence_and_enrich_adds_guidance() {
    use crate::model::Origin;
    let mut sub = TestSubstrate::new();
    // A contradiction gives a deterministic finding whose cited evidence seeds
    // the DISCOVER bundle.
    let h1 = sub.add_fact("acme", "deploy_target", "us-east-1");
    let _h2 = sub.add_fact("acme", "deploy_target", "eu-west-1");

    // One draft cites a real evidence hash (kept); one cites a bogus hash
    // (dropped as uncited before the verifier even runs).
    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"prod region is ambiguous","target":"entity:test/acme","guidance":"pick one","evidence":["{h1}"],"confidence":0.9}},
          {{"summary":"uncited nonsense","target":"entity:test/acme","evidence":["deadbeef"],"confidence":0.9}}
        ]}}"#
    );
    // After validation only the cited draft remains → verifier id 0.
    let ground = r#"{"results":[{"id":0,"supported":true,"reason":"entailed"}]}"#.to_string();
    let verify =
        r#"{"results":[{"id":0,"keep":true,"confidence":0.88,"reason":"novel and real"}]}"#.to_string();
    let enrich =
        r#"{"notes":[{"target":"entity:test/acme","guidance":"resolve to latest"}]}"#.to_string();

    let e = Engine::with_builtins().with_llm(Box::new(MockLlm { discover, ground, verify, enrich }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = e.recommendations(&sub.inner, None).unwrap();

    // Exactly one llm-origin rec — cited, grounded, verified.
    let llm: Vec<_> = recs
        .iter()
        .filter(|r| matches!(r.origin, Origin::Llm { .. }))
        .collect();
    assert_eq!(llm.len(), 1, "only the cited+grounded+verified draft survives");
    assert!(llm[0].summary.render().contains("ambiguous"));
    assert_eq!(llm[0].evidence, vec![h1.clone()]);
    // The verifier's calibrated confidence is stamped (not a hardcoded default).
    assert!((llm[0].confidence - 0.88).abs() < 1e-9, "conf {}", llm[0].confidence);
    assert!(!llm[0].destructive);
    assert_eq!(llm[0].status, RecStatus::Pending);

    // ENRICH added a whitelisted guidance note to the deterministic finding
    // without touching its templated summary.
    let det = recs
        .iter()
        .find(|r| r.analyzer.starts_with("loop.contradiction"))
        .expect("a contradiction recommendation");
    assert_eq!(det.guidance.as_deref(), Some("resolve to latest"));
    assert!(det.summary.render().contains("deploy_target"));

    // §6b approval-rate metric: one surfaced llm proposal, still undecided.
    let m = e.llm_metrics(&sub.inner).unwrap();
    assert_eq!(m.proposed, 1);
    assert_eq!(m.pending, 1);
    assert_eq!(m.approval_rate, None);
}

#[test]
fn verifier_drops_ungrounded_and_low_confidence_drafts() {
    use crate::model::Origin;
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("acme", "deploy_target", "us-east-1");
    let _h2 = sub.add_fact("acme", "deploy_target", "eu-west-1");
    // Two cited drafts pass validation → verifier ids 0 and 1.
    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"grounded but the verifier is unsure","target":"entity:test/acme","evidence":["{h1}"],"confidence":0.9}},
          {{"summary":"an ungrounded claim","target":"entity:test/acme","evidence":["{h1}"],"confidence":0.9}}
        ]}}"#
    );
    // Grounding: id 0 supported, id 1 NOT — id 1 never reaches verify.
    let ground =
        r#"{"results":[{"id":0,"supported":true},{"id":1,"supported":false}]}"#.to_string();
    // Verify (only id 0): kept, but confidence 0.5 is below the 0.75 floor → dropped.
    let verify = r#"{"results":[{"id":0,"keep":true,"confidence":0.5}]}"#.to_string();
    let enrich = r#"{"notes":[]}"#.to_string();

    let e = Engine::with_builtins().with_llm(Box::new(MockLlm { discover, ground, verify, enrich }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = e.recommendations(&sub.inner, None).unwrap();
    assert!(
        recs.iter().all(|r| !matches!(r.origin, Origin::Llm { .. })),
        "ungrounded (id 1) and below-floor (id 0) drafts never reach the queue"
    );
}

#[test]
fn separate_ground_backend_is_consulted_for_grounding() {
    use crate::model::Origin;
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("acme", "deploy_target", "us-east-1");
    let _h2 = sub.add_fact("acme", "deploy_target", "eu-west-1");
    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"grounded per the main model","target":"entity:test/acme","evidence":["{h1}"],"confidence":0.9}}
        ]}}"#
    );
    // The MAIN backend would ground (supported:true) and keep the draft.
    let main = MockLlm {
        discover,
        ground: r#"{"results":[{"id":0,"supported":true}]}"#.to_string(),
        verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9}]}"#.to_string(),
        enrich: r#"{"notes":[]}"#.to_string(),
    };
    // The SEPARATE ground backend REJECTS (supported:false). If it — not the main
    // backend — is the one consulted for GROUND, the draft dies before verify.
    let ground = MockLlm {
        discover: String::new(),
        ground: r#"{"results":[{"id":0,"supported":false}]}"#.to_string(),
        verify: String::new(),
        enrich: String::new(),
    };
    let e = Engine::with_builtins()
        .with_llm(Box::new(main))
        .with_ground_llm(Box::new(ground));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = e.recommendations(&sub.inner, None).unwrap();
    assert!(
        recs.iter().all(|r| !matches!(r.origin, Origin::Llm { .. })),
        "the separate ground backend's rejection gates the draft"
    );
}

#[test]
fn llm_authored_lesson_is_applicable_and_rolls_back() {
    use crate::model::{ActionKind, Origin};
    use crate::recommendation::Proposal;
    use crate::substrate::SubstrateRead;
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("acme", "deploy_target", "us-east-1");
    let _h2 = sub.add_fact("acme", "deploy_target", "eu-west-1");

    // Three lesson-bearing drafts: (0) an entity target — becomes applicable
    // (the embedded control chars must be collapsed, never stored); (1) a
    // query target — a lesson Fact has no subject there, stays advisory;
    // (2) an over-long lesson — capped at MAX_LESSON_LEN.
    let long_lesson = "y".repeat(400);
    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"the region conflict keeps recurring","target":"entity:test/acme","guidance":"","evidence":["{h1}"],"confidence":0.9,"lesson":"Confirm the deploy region\nbefore writing it"}},
          {{"summary":"query needs a tighter filter","target":"query:cleanup","evidence":["{h1}"],"confidence":0.9,"lesson":"Scope the cleanup query"}},
          {{"summary":"long-winded advice","target":"entity:test/acme2","evidence":["{h1}"],"confidence":0.9,"lesson":"{long_lesson}"}}
        ]}}"#
    );
    let ground = r#"{"results":[{"id":0,"supported":true},{"id":1,"supported":true},{"id":2,"supported":true}]}"#.to_string();
    let verify = r#"{"results":[{"id":0,"keep":true,"confidence":0.9},{"id":1,"keep":true,"confidence":0.9},{"id":2,"keep":true,"confidence":0.9}]}"#.to_string();
    let enrich = r#"{"notes":[]}"#.to_string();

    let e = Engine::with_builtins().with_llm(Box::new(MockLlm { discover, ground, verify, enrich }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = e.recommendations(&sub.inner, None).unwrap();

    // Draft 0: applicable — an ADD fact of the sanitized lesson, in the
    // evidence's namespace, reviewable with the lesson in the summary.
    let lesson_rec = recs
        .iter()
        .find(|r| {
            matches!(r.origin, Origin::Llm { .. }) && r.target_ref == "entity:test/acme"
        })
        .expect("the entity-target lesson rec");
    assert_eq!(lesson_rec.action_kind, ActionKind::ClusterFailure);
    assert!(lesson_rec.rollbackable && !lesson_rec.destructive);
    assert_eq!(lesson_rec.status, RecStatus::Pending);
    let Proposal::Cal { cal } = &lesson_rec.proposal else {
        panic!("authored lesson must be a CAL proposal, got {:?}", lesson_rec.proposal);
    };
    assert!(cal.starts_with("ADD fact "), "{cal}");
    assert!(cal.contains(r#""relation":"lesson""#), "{cal}");
    assert!(
        cal.contains("Confirm the deploy region before writing it"),
        "control chars collapse to spaces: {cal}"
    );
    assert!(cal.contains(r#""subject":"acme""#), "{cal}");
    assert!(
        cal.contains(r#""namespace":"test""#),
        "lesson lands in the evidence's namespace: {cal}"
    );
    assert!(
        lesson_rec.summary.render().contains("Confirm the deploy region"),
        "the reviewer sees the exact line an apply would record"
    );

    // Draft 1: lesson on a query target stays an advisory flag.
    let advisory = recs
        .iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }) && r.target_ref == "query:cleanup")
        .expect("the query-target rec");
    assert_eq!(advisory.action_kind, ActionKind::Flag);
    assert!(!advisory.rollbackable);
    assert!(matches!(advisory.proposal, Proposal::Data { .. }));

    // Draft 2: the lesson text is capped.
    let capped = recs
        .iter()
        .find(|r| {
            matches!(r.origin, Origin::Llm { .. }) && r.target_ref == "entity:test/acme2"
        })
        .expect("the over-long lesson rec");
    let Proposal::Cal { cal } = &capped.proposal else { panic!("expected CAL") };
    assert!(
        !cal.contains(&"y".repeat(crate::llm::MAX_LESSON_LEN + 1)),
        "lesson capped at MAX_LESSON_LEN"
    );

    // The governed round trip: approve with a BECAUSE, apply, roll back —
    // the exact machinery deterministic lessons use.
    e.review(
        &mut sub.inner,
        &lesson_rec.hash,
        Decision::Approve,
        "user:reviewer",
        ObserverType::Human,
        &ScopeSet::all(),
        "grounded and useful",
        11_000,
    )
    .unwrap();
    let applied = e
        .apply(
            &mut sub.inner,
            &lesson_rec.hash,
            "user:reviewer",
            ObserverType::Human,
            &ScopeSet::all(),
            "recording the lesson",
            false, // an authored lesson never needs the destructive override
            12_000,
        )
        .unwrap();
    assert_eq!(applied.created_hashes.len(), 1, "one lesson Fact created");
    let g = sub.inner.grain(&applied.created_hashes[0]).unwrap().expect("lesson grain");
    assert_eq!(g.fact_relation(), Some("lesson"));
    assert_eq!(g.fact_subject(), Some("acme"));
    assert!(g.is_live());

    e.rollback(
        &mut sub.inner,
        &lesson_rec.hash,
        "user:reviewer",
        ObserverType::Human,
        &ScopeSet::all(),
        "measured regression",
        13_000,
    )
    .unwrap();
    let g = sub.inner.grain(&applied.created_hashes[0]).unwrap();
    assert!(
        g.is_none_or(|g| !g.is_live()),
        "rollback retracts the authored lesson"
    );
}

/// A human's note must reach the model even when routine records outnumber
/// it hundreds to one.
///
/// This is the shape that matters: a supervisor states a rule ONCE, and the
/// desk then generates thousands of ordinary grains. Seeding the evidence
/// bundle by recency or frequency buries exactly the rarest and most
/// valuable signal, and the symptom is indistinguishable from a model that
/// had nothing to say.
#[test]
fn a_lone_human_observation_survives_a_flood_of_routine_facts() {
    use std::sync::{Arc, Mutex};
    let mut sub = TestSubstrate::new();
    // The note, written early — then buried.
    sub.add_observation("test", "Note from the billing lead: from now on any refund over $500 must ALSO be logged as a case with priority high.");
    for i in 0..300 {
        sub.add_fact(&format!("task-{i:04}"), "episode", "{\"outcome\":\"accepted\"}");
    }
    // Enough of one failure shape to give the analyzers something to cite.
    for _ in 0..8 {
        sub.add_tool_call("refund", true, "{\"error\":{\"code\":\"rate_limited\"}}");
    }
    sub.add_tool_call("refund", false, "{\"refund_id\":\"re_1\"}");

    let seen: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
    struct Capture(Arc<Mutex<String>>);
    impl crate::llm::LlmBackend for Capture {
        fn model(&self) -> &str { "capture" }
        fn complete(&self, request: &str) -> crate::error::Result<String> {
            if request.contains("\"op\":\"discover\"") {
                *self.0.lock().unwrap() = request.to_string();
            }
            Ok(r#"{"recommendations":[]}"#.to_string())
        }
    }
    let e = Engine::with_builtins().with_llm(Box::new(Capture(seen.clone())));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();

    let req = seen.lock().unwrap().clone();
    assert!(!req.is_empty(), "DISCOVER was never called");
    assert!(
        req.contains("billing lead"),
        "the human note never reached the evidence bundle — 300 routine facts          crowded out the one grain a person wrote"
    );
}

/// The funnel has to tell apart the ways "the model contributed nothing"
/// can happen, because they call for opposite responses and every one of
/// them renders as an empty ledger.
#[test]
fn the_llm_funnel_separates_abstention_from_each_gate() {
    let draft = |h: &str| format!(
        r#"{{"recommendations":[{{"summary":"s","target":"entity:test/acme","evidence":["{h}"],"confidence":0.9}}]}}"#
    );
    // The cite-check drops any draft naming a hash the bundle does not hold,
    // so a test of the LATER gates has to cite a real one.
    let real_hash = {
        let mut sub = TestSubstrate::new();
        let h = sub.add_fact("acme", "deploy_target", "us-east-1");
        sub.add_fact("acme", "deploy_target", "eu-west-1");
        h
    };
    let run = |discover: String, ground: &str, verify: &str| {
        let mut sub = TestSubstrate::new();
        sub.add_fact("acme", "deploy_target", "us-east-1");
        sub.add_fact("acme", "deploy_target", "eu-west-1");
        let e = Engine::with_builtins().with_llm(Box::new(MockLlm {
            discover,
            ground: ground.to_string(),
            verify: verify.to_string(),
            enrich: r#"{"notes":[]}"#.to_string(),
        }));
        let r = e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
        r.llm_funnel.expect("a funnel whenever a backend is attached")
    };

    // The model abstained: evidence was offered, nothing came back.
    let f = run(r#"{"recommendations":[]}"#.to_string(), "", "");
    assert!(f.evidence > 0, "evidence was offered");
    assert_eq!((f.proposed, f.stored), (0, 0), "abstention: nothing proposed");

    // Proposed, but uncited — dropped before any model call.
    let f = run(draft("deadbeef"), "", "");
    assert_eq!((f.proposed, f.cited), (1, 0), "uncited drafts die at the cite-check");

    // Cited, then refused by GROUND.
    let f = run(
        draft(&real_hash),
        r#"{"results":[{"id":0,"supported":false}]}"#,
        r#"{"results":[{"id":0,"keep":true,"confidence":0.9}]}"#,
    );
    assert_eq!(f.grounded, 0, "GROUND rejection is visible as its own stage");

    // Grounded, then killed by VERIFY.
    let f = run(
        draft(&real_hash),
        r#"{"results":[{"id":0,"supported":true}]}"#,
        r#"{"results":[{"id":0,"keep":false,"confidence":0.9}]}"#,
    );
    assert_eq!((f.grounded, f.kept, f.stored), (1, 0, 0), "VERIFY kill is distinct");

    // Kept, but under the confidence floor.
    let f = run(
        draft(&real_hash),
        r#"{"results":[{"id":0,"supported":true}]}"#,
        r#"{"results":[{"id":0,"keep":true,"confidence":0.10}]}"#,
    );
    assert_eq!((f.kept, f.stored), (1, 0), "the floor is its own stage");
}

#[test]
fn llm_authored_fact_records_a_model_chosen_relation() {
    use crate::model::{ActionKind, Origin};
    use crate::recommendation::Proposal;
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("acme", "invoice_vendor", "Cobolt Cloud");
    let _h2 = sub.add_fact("acme", "invoice_vendor", "Cobalt Cloud");

    // (0) a well-formed fact; (1) a relation that is prose, not an identifier
    // — it would become an unfindable predicate, so the draft goes advisory;
    // (2) an empty object — nothing to record.
    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"the same misspelling keeps arriving","target":"entity:test/acme","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"fact","relation":"alias_of","object":"Cobalt Cloud"}}}},
          {{"summary":"prose relation","target":"entity:test/acme2","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"fact","relation":"is usually spelled","object":"Cobalt Cloud"}}}},
          {{"summary":"empty object","target":"entity:test/acme3","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"fact","relation":"alias_of","object":"   "}}}}
        ]}}"#
    );
    let ground = r#"{"results":[{"id":0,"supported":true},{"id":1,"supported":true},{"id":2,"supported":true}]}"#.to_string();
    let verify = r#"{"results":[{"id":0,"keep":true,"confidence":0.9},{"id":1,"keep":true,"confidence":0.9},{"id":2,"keep":true,"confidence":0.9}]}"#.to_string();
    let e = Engine::with_builtins().with_llm(Box::new(MockLlm {
        discover,
        ground,
        verify,
        enrich: r#"{"notes":[]}"#.to_string(),
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = e.recommendations(&sub.inner, None).unwrap();

    let fact = recs
        .iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }) && r.target_ref == "entity:test/acme")
        .expect("the fact rec");
    assert_eq!(fact.action_kind, ActionKind::Record);
    assert!(fact.rollbackable && !fact.destructive);
    let Proposal::Cal { cal } = &fact.proposal else {
        panic!("a fact proposal is CAL, got {:?}", fact.proposal)
    };
    assert!(cal.starts_with("ADD fact "), "{cal}");
    assert!(cal.contains(r#""relation":"alias_of""#), "{cal}");
    assert!(cal.contains(r#""object":"Cobalt Cloud""#), "{cal}");
    // Subject from the TARGET and namespace from the EVIDENCE — the model
    // named neither.
    assert!(cal.contains(r#""subject":"acme""#), "{cal}");
    assert!(cal.contains(r#""namespace":"test""#), "{cal}");
    // The grain carries the VERIFIER's confidence, not the proposer's 0.9.
    assert!(cal.contains(r#""confidence":0.9"#), "{cal}");
    assert!(
        fact.summary.render().contains("alias_of"),
        "the reviewer sees the relation an apply would write: {}",
        fact.summary.render()
    );

    for (target, why) in [
        ("entity:test/acme2", "a prose relation is not a predicate"),
        ("entity:test/acme3", "an empty object records nothing"),
    ] {
        let r = recs
            .iter()
            .find(|r| matches!(r.origin, Origin::Llm { .. }) && r.target_ref == target)
            .unwrap_or_else(|| panic!("expected an advisory rec for {target}"));
        assert_eq!(r.action_kind, ActionKind::Flag, "{why}");
        assert!(matches!(r.proposal, Proposal::Data { .. }), "{why}");
    }
}

#[test]
fn llm_query_revision_is_applicable_only_with_a_recorded_inverse() {
    use crate::model::{ActionKind, Origin};
    use crate::recommendation::Proposal;
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("acme", "deploy_target", "us-east-1");
    let _h2 = sub.add_fact("acme", "deploy_target", "eu-west-1");

    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"the briefing query misses the lessons","target":"query:desk_pulse","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"query_revision","body":"RECALL facts WHERE relation = \"lesson\" LIMIT 20"}}}},
          {{"summary":"empty body","target":"query:empty","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"query_revision","body":"  "}}}}
        ]}}"#
    );
    let ground = r#"{"results":[{"id":0,"supported":true},{"id":1,"supported":true}]}"#.to_string();
    let verify = r#"{"results":[{"id":0,"keep":true,"confidence":0.9},{"id":1,"keep":true,"confidence":0.9}]}"#.to_string();
    let e = Engine::with_builtins().with_llm(Box::new(MockLlm {
        discover,
        ground,
        verify,
        enrich: r#"{"notes":[]}"#.to_string(),
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = e.recommendations(&sub.inner, None).unwrap();

    let rev = recs
        .iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }) && r.target_ref == "query:desk_pulse")
        .expect("the query revision rec");
    assert_eq!(rev.action_kind, ActionKind::Revise);
    assert!(rev.rollbackable && !rev.destructive);
    let Proposal::Cal { cal } = &rev.proposal else {
        panic!("a query revision is CAL, got {:?}", rev.proposal)
    };
    // The NAME comes from the target; only the body came from the model.
    assert!(cal.starts_with(r#"DEFINE QUERY "desk_pulse" AS { "#), "{cal}");
    assert!(cal.contains("relation = \"lesson\""), "{cal}");
    assert!(!cal.contains('\n'), "a definition is one statement: {cal}");

    // An empty body is nothing to define.
    let empty = recs
        .iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }) && r.target_ref == "query:empty")
        .expect("the empty-body rec");
    assert_eq!(empty.action_kind, ActionKind::Flag);

    // Governed apply: the DEFINE runs, and the recorded inverse is what makes
    // it applicable at all.
    e.review(
        &mut sub.inner,
        &rev.hash,
        Decision::Approve,
        "user:reviewer",
        ObserverType::Human,
        &ScopeSet::all(),
        "the briefing should carry the lessons",
        11_000,
    )
    .unwrap();
    e.apply(
        &mut sub.inner,
        &rev.hash,
        "user:reviewer",
        ObserverType::Human,
        &ScopeSet::all(),
        "applying the tighter briefing",
        false,
        12_000,
    )
    .unwrap();
    e.rollback(
        &mut sub.inner,
        &rev.hash,
        "user:reviewer",
        ObserverType::Human,
        &ScopeSet::all(),
        "reverting",
        13_000,
    )
    .unwrap();
}

#[test]
fn llm_plan_revision_edits_fields_and_refuses_topology_and_staleness() {
    use crate::model::{ActionKind, Origin};
    use crate::recommendation::Proposal;
    let mut sub = TestSubstrate::new();
    let plan = sub.add_workflow();
    let h1 = sub.add_fact("acme", "deploy_target", "us-east-1");
    let _h2 = sub.add_fact("acme", "deploy_target", "eu-west-1");

    // (0) two legal edits; (1) a topology rewrite; (2) a stale `from`;
    // (3) a no-op. Only (0) may become applicable.
    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"the review cycle is too tight","target":"grain:{plan}","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"plan_revision","edits":[
              {{"path":"edges.1.max_cycles","from":2,"to":4}},
              {{"path":"retries.fetch","from":1,"to":3}}]}}}},
          {{"summary":"rewire it","target":"grain:{plan}","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"plan_revision","edits":[{{"path":"edges.0.dst","from":"review","to":"post"}}]}}}},
          {{"summary":"authored against an older plan","target":"grain:{plan}","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"plan_revision","edits":[{{"path":"edges.1.max_cycles","from":9,"to":4}}]}}}},
          {{"summary":"changes nothing","target":"grain:{plan}","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"plan_revision","edits":[{{"path":"retries.fetch","from":1,"to":1}}]}}}}
        ]}}"#
    );
    let ground = r#"{"results":[{"id":0,"supported":true},{"id":1,"supported":true},{"id":2,"supported":true},{"id":3,"supported":true}]}"#.to_string();
    let verify = r#"{"results":[{"id":0,"keep":true,"confidence":0.9},{"id":1,"keep":true,"confidence":0.9},{"id":2,"keep":true,"confidence":0.9},{"id":3,"keep":true,"confidence":0.9}]}"#.to_string();
    let e = Engine::with_builtins().with_llm(Box::new(MockLlm {
        discover,
        ground,
        verify,
        enrich: r#"{"notes":[]}"#.to_string(),
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = e.recommendations(&sub.inner, None).unwrap();

    // All four share one target, so dedup keeps ONE rec per (family, target,
    // action) — the applicable Revise is the one that resolved.
    let plan_recs: Vec<_> = recs
        .iter()
        .filter(|r| matches!(r.origin, Origin::Llm { .. }) && r.target_ref == format!("grain:{plan}"))
        .collect();
    let revise = plan_recs
        .iter()
        .find(|r| r.action_kind == ActionKind::Revise)
        .expect("the legal plan revision");
    let Proposal::Cal { cal } = &revise.proposal else {
        panic!("a plan revision is CAL, got {:?}", revise.proposal)
    };
    assert!(cal.starts_with(&format!("SUPERSEDE {plan} WITH workflow ")), "{cal}");
    assert!(cal.contains(r#""max_cycles":4"#), "the edit landed: {cal}");
    assert!(cal.contains(r#""fetch":3"#), "the retry edit landed: {cal}");
    // Untouched topology travels through verbatim.
    assert!(cal.contains(r#""dst":"review""#), "topology preserved: {cal}");
    assert!(
        revise.summary.render().contains("edges.1.max_cycles: 2 -> 4"),
        "the reviewer sees the deltas, not a re-drawn graph: {}",
        revise.summary.render()
    );

    // The topology, stale and no-op drafts all failed to resolve — they are
    // advisory, and none of them minted a second executable plan proposal.
    assert_eq!(
        plan_recs.iter().filter(|r| r.action_kind == ActionKind::Revise).count(),
        1,
        "only the legal edit set is executable"
    );
}

#[test]
fn llm_code_revision_pins_the_tools_declared_evalset() {
    use crate::model::{ActionKind, Origin};
    use crate::recommendation::Proposal;
    let mut sub = TestSubstrate::new();
    let evalset = sub.add_fact("evalset:screen", "mg:evalset", r#"{"cases":[]}"#);
    sub.add_tool_def("screen_payment", Some(&evalset));
    sub.add_tool_def("unpinned_tool", None);
    let h1 = sub.add_tool_call("screen_payment", true, "missed an exact match");
    let _h2 = sub.add_tool_call("screen_payment", true, "missed an exact match");

    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"the matcher misses exact hits","target":"tool:screen_payment","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"code_revision","source":"def screen(p):\n    return exact_match(p)"}}}},
          {{"summary":"same for the unpinned one","target":"tool:unpinned_tool","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"code_revision","source":"def f(): pass"}}}},
          {{"summary":"a tool target with no code proposal","target":"tool:screen_payment","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"lesson","lesson":"Check exact matches first"}}}}
        ]}}"#
    );
    let ground = r#"{"results":[{"id":0,"supported":true}]}"#.to_string();
    let verify = r#"{"results":[{"id":0,"keep":true,"confidence":0.92}]}"#.to_string();
    let e = Engine::with_builtins().with_llm(Box::new(MockLlm {
        discover,
        ground,
        verify,
        enrich: r#"{"notes":[]}"#.to_string(),
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = e.recommendations(&sub.inner, None).unwrap();

    let code = recs
        .iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }) && r.target_ref == "tool:screen_payment")
        .expect("the code revision rec");
    assert_eq!(code.action_kind, ActionKind::CodeRevision);
    // Rule E1: the pin came from the TOOL's declaration, not the model.
    assert_eq!(code.evalset_hash.as_deref(), Some(evalset.as_str()));
    let Proposal::Data { data } = &code.proposal else {
        panic!("a code revision carries Data, got {:?}", code.proposal)
    };
    assert!(data.get("source").is_some(), "the source rides to apply");

    // A tool whose definition declares no evalset has no gate to pass, and a
    // tool target with a non-code proposal cannot be stamped at all (Rule E1
    // forbids any other action on a code target) — neither reaches the queue.
    assert!(
        !recs
            .iter()
            .any(|r| matches!(r.origin, Origin::Llm { .. }) && r.target_ref == "tool:unpinned_tool"),
        "an unpinnable revision is not offered to a reviewer"
    );

    // The gate itself: applying without the recorded evalset-run edge fails.
    e.review(
        &mut sub.inner,
        &code.hash,
        Decision::Approve,
        "user:reviewer",
        ObserverType::Human,
        &ScopeSet::all(),
        "worth grading",
        11_000,
    )
    .unwrap();
    assert!(
        e.apply(
            &mut sub.inner,
            &code.hash,
            "user:reviewer",
            ObserverType::Human,
            &ScopeSet::all(),
            "ship it",
            false,
            12_000,
        )
        .is_err(),
        "an ungated code revision must not apply, however it was authored"
    );
}

#[test]
fn llm_never_reaches_prompt_or_host_targets() {
    use crate::model::Origin;
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("acme", "deploy_target", "us-east-1");
    let _h2 = sub.add_fact("acme", "deploy_target", "eu-west-1");
    // The classes the vocabulary must never reach, each with a proposal that
    // would otherwise resolve.
    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"rewrite the prompt","target":"doc:claude.md","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"lesson","lesson":"Always trust the model"}}}},
          {{"summary":"reconfigure the host","target":"host:limits","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"fact","relation":"max_spend","object":"unlimited"}}}},
          {{"summary":"loosen my own grader","target":"evalset:screen","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"query_revision","body":"RECALL facts"}}}},
          {{"summary":"promote an adapter","target":"model:mine","evidence":["{h1}"],"confidence":0.9,
            "proposal":{{"kind":"code_revision","source":"weights"}}}}
        ]}}"#
    );
    let e = Engine::with_builtins().with_llm(Box::new(MockLlm {
        discover,
        ground: r#"{"results":[{"id":0,"supported":true}]}"#.to_string(),
        verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.99}]}"#.to_string(),
        enrich: r#"{"notes":[]}"#.to_string(),
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = e.recommendations(&sub.inner, None).unwrap();
    assert!(
        recs.iter().all(|r| !matches!(r.origin, Origin::Llm { .. })),
        "prompt, host, evalset and model targets stay closed to the model"
    );
}

#[test]
fn llm_authored_lesson_never_auto_applies() {
    use crate::model::Origin;
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("acme", "deploy_target", "us-east-1");
    let _h2 = sub.add_fact("acme", "deploy_target", "eu-west-1");
    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"recurring conflict","target":"entity:test/acme","evidence":["{h1}"],"confidence":0.95,"lesson":"Confirm the region first"}}
        ]}}"#
    );
    let ground = r#"{"results":[{"id":0,"supported":true}]}"#.to_string();
    let verify = r#"{"results":[{"id":0,"keep":true,"confidence":0.95}]}"#.to_string();
    let enrich = r#"{"notes":[]}"#.to_string();
    // A policy that names the llm family outright — the widest grant a host
    // could misconfigure. Origin::Llm, the missing manifest, and the ADD
    // shape check must each independently keep the lesson Pending.
    let policy = Policy::from_json(
        r#"{"auto_apply_enabled": true,
            "auto_apply": [{"analyzer": "loop.llm", "targets": ["memory"], "max_severity": "high"}]}"#,
    )
    .unwrap();
    let e = Engine::with_builtins()
        .with_policy(policy)
        .with_llm(Box::new(MockLlm { discover, ground, verify, enrich }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = e.recommendations(&sub.inner, None).unwrap();
    let rec = recs
        .iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }))
        .expect("the lesson rec");
    assert_eq!(
        rec.status,
        RecStatus::Pending,
        "an authored lesson never auto-applies, whatever the policy grants"
    );
}

#[test]
fn ground_and_verify_judge_the_lesson_text_not_just_the_summary() {
    use std::sync::{Arc, Mutex};
    struct RecordingLlm {
        inner: MockLlm,
        seen: Arc<Mutex<Vec<String>>>,
    }
    impl crate::llm::LlmBackend for RecordingLlm {
        fn model(&self) -> &str {
            "recording-mock"
        }
        fn complete(&self, request: &str) -> crate::error::Result<String> {
            self.seen.lock().unwrap().push(request.to_string());
            self.inner.complete(request)
        }
    }
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("acme", "deploy_target", "us-east-1");
    let _h2 = sub.add_fact("acme", "deploy_target", "eu-west-1");
    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"recurring conflict","target":"entity:test/acme","evidence":["{h1}"],"confidence":0.9,"lesson":"Confirm the region first"}}
        ]}}"#
    );
    let seen = Arc::new(Mutex::new(Vec::new()));
    let e = Engine::with_builtins().with_llm(Box::new(RecordingLlm {
        inner: MockLlm {
            discover,
            ground: r#"{"results":[{"id":0,"supported":true}]}"#.to_string(),
            verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9}]}"#.to_string(),
            enrich: r#"{"notes":[]}"#.to_string(),
        },
        seen: Arc::clone(&seen),
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let seen = seen.lock().unwrap();
    for op in ["\"op\":\"ground\"", "\"op\":\"verify\""] {
        let req = seen
            .iter()
            .find(|r| r.contains(op))
            .unwrap_or_else(|| panic!("no {op} request recorded"));
        assert!(
            req.contains("Proposed lesson to record") && req.contains("Confirm the region first"),
            "{op} must see the authored lesson, got: {req}"
        );
    }
}

/// A fold summary reaches the LLM lens, and nothing else in `agent:harness`
/// does.
///
/// Both halves matter. An all-namespace scan hides every `agent:` namespace on
/// purpose — those hold the file's grants and Tier-2 audit records, and an
/// analyzer that swept them as ordinary memory once proposed tombstoning the
/// grants. But a fold summary is the agent's own account of a long run, and
/// living behind that exclusion made it unreadable to the one consumer it was
/// written for: measured against a real model, the lens saw `evidence: 0` and
/// DISCOVER was never called.
///
/// So the carve-out is by explicit namespace AND an explicit kind list. This
/// test pins both directions — a governance record in the same namespace must
/// stay invisible, or the fix has quietly become the sweep it avoided.
#[test]
fn a_fold_summary_reaches_the_llm_lens_and_governance_records_do_not() {
    use serde_json::json;
    use std::sync::{Arc, Mutex};
    struct RecordingLlm {
        inner: MockLlm,
        seen: Arc<Mutex<Vec<String>>>,
    }
    impl crate::llm::LlmBackend for RecordingLlm {
        fn model(&self) -> &str {
            "recording-mock"
        }
        fn complete(&self, request: &str) -> crate::error::Result<String> {
            self.seen.lock().unwrap().push(request.to_string());
            self.inner.complete(request)
        }
    }

    let mut sub = TestSubstrate::new();
    let fold = sub.put_observation(
        crate::eval::HARNESS_NS,
        &[
            ("observation_kind", json!("fold_summary")),
            ("run_id", json!("r-1")),
            ("object", json!("the Rotterdam depot rejects pallets over 1200mm")),
        ],
    );
    // Same namespace, NOT on the list: an audit record the lens must not see.
    sub.put_observation(
        crate::eval::HARNESS_NS,
        &[
            ("observation_kind", json!("egress_refusal")),
            ("object", json!("https://blocked.example refused by policy")),
        ],
    );

    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"pallet height keeps causing rejections",
            "target":"entity:logistics/pallet_height","evidence":["{fold}"],
            "confidence":0.9,"lesson":"Check pallet height before dispatch"}}
        ]}}"#
    );
    let seen = Arc::new(Mutex::new(Vec::new()));
    let e = Engine::with_builtins().with_llm(Box::new(RecordingLlm {
        inner: MockLlm {
            discover,
            ground: r#"{"results":[{"id":0,"supported":true}]}"#.to_string(),
            verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9}]}"#.to_string(),
            enrich: r#"{"notes":[]}"#.to_string(),
        },
        seen: Arc::clone(&seen),
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();

    let seen = seen.lock().unwrap();
    let discover_req = seen
        .iter()
        .find(|r| r.contains("\"op\":\"discover\""))
        .expect("DISCOVER must be called — an empty bundle skips it entirely");
    assert!(
        discover_req.contains("Rotterdam depot rejects pallets over 1200mm"),
        "the fold summary must reach the lens: {discover_req}"
    );
    assert!(
        !discover_req.contains("blocked.example"),
        "a governance record in the same namespace must stay hidden: {discover_req}"
    );
}

#[test]
fn human_note_evidence_reaches_the_llm_with_text() {
    use std::sync::{Arc, Mutex};
    struct RecordingLlm {
        inner: MockLlm,
        seen: Arc<Mutex<Vec<String>>>,
    }
    impl crate::llm::LlmBackend for RecordingLlm {
        fn model(&self) -> &str {
            "recording-mock"
        }
        fn complete(&self, request: &str) -> crate::error::Result<String> {
            self.seen.lock().unwrap().push(request.to_string());
            self.inner.complete(request)
        }
    }
    let mut sub = TestSubstrate::new();
    // A human note is stored as subject + object with NO relation, so it
    // misses grain_brief's fact-triple branch. It must still render.
    sub.add_human_note(
        "expense",
        "expense_capture",
        "user:billing-lead",
        "I also need the vendor, the amount and the currency on every one.",
    );
    for _ in 0..5 {
        sub.add_tool_call("stripe_refund", true, "rate_limited 429");
    }
    let seen = Arc::new(Mutex::new(Vec::new()));
    let e = Engine::with_builtins().with_llm(Box::new(RecordingLlm {
        inner: MockLlm {
            discover: r#"{"recommendations":[]}"#.to_string(),
            ground: r#"{"results":[]}"#.to_string(),
            verify: r#"{"results":[]}"#.to_string(),
            enrich: r#"{"notes":[]}"#.to_string(),
        },
        seen: Arc::clone(&seen),
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let seen = seen.lock().unwrap();
    let discover = seen
        .iter()
        .find(|r| r.contains("\"op\":\"discover\""))
        .expect("a discover request");
    let v: serde_json::Value = serde_json::from_str(discover).unwrap();
    let notes: Vec<_> = v["evidence"]
        .as_array()
        .expect("evidence array")
        .iter()
        .filter(|i| i["grain_type"] == "observation")
        .collect();
    assert!(!notes.is_empty(), "the human note reaches the bundle");
    for item in notes {
        let text = item["text"].as_str().unwrap_or("");
        // Found live against a real memory: every human Observation reached
        // the model as "" — the highest-value evidence a memory holds was the
        // one shape that rendered to nothing, so an explicit instruction from
        // a person could never become a lesson.
        assert!(
            text.contains("vendor") && text.contains("currency"),
            "human-note evidence must carry its text, got: {text:?}"
        );
    }
}

#[test]
fn tool_grain_evidence_reaches_the_llm_with_text() {
    use std::sync::{Arc, Mutex};
    struct RecordingLlm {
        inner: MockLlm,
        seen: Arc<Mutex<Vec<String>>>,
    }
    impl crate::llm::LlmBackend for RecordingLlm {
        fn model(&self) -> &str {
            "recording-mock"
        }
        fn complete(&self, request: &str) -> crate::error::Result<String> {
            self.seen.lock().unwrap().push(request.to_string());
            self.inner.complete(request)
        }
    }
    let mut sub = TestSubstrate::new();
    // A dominant failure cluster: the tool_failure candidate cites these tool
    // grains, which seeds them into the DISCOVER evidence bundle.
    for _ in 0..5 {
        sub.add_tool_call("stripe_refund", true, "rate_limited 429");
    }
    let seen = Arc::new(Mutex::new(Vec::new()));
    let e = Engine::with_builtins().with_llm(Box::new(RecordingLlm {
        inner: MockLlm {
            discover: r#"{"recommendations":[]}"#.to_string(),
            ground: r#"{"results":[]}"#.to_string(),
            verify: r#"{"results":[]}"#.to_string(),
            enrich: r#"{"notes":[]}"#.to_string(),
        },
        seen: Arc::clone(&seen),
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let seen = seen.lock().unwrap();
    let discover = seen
        .iter()
        .find(|r| r.contains("\"op\":\"discover\""))
        .expect("a discover request");
    let v: serde_json::Value = serde_json::from_str(discover).unwrap();
    let items = v["evidence"].as_array().expect("evidence array");
    let tools: Vec<_> =
        items.iter().filter(|i| i["grain_type"] == "tool").collect();
    assert!(!tools.is_empty(), "tool grains reach the bundle");
    for item in tools {
        let text = item["text"].as_str().unwrap_or("");
        // Found live: tool grains rendered as EMPTY text, so GROUND rightly
        // refused to ground a correct lesson against evidence it couldn't
        // see. The brief must carry the tool name and the failure body.
        assert!(
            text.contains("stripe_refund") && text.contains("rate_limited"),
            "tool evidence must carry name + outcome, got: {text:?}"
        );
    }
}

#[test]
fn llm_sees_tool_failures_no_analyzer_flagged() {
    use std::sync::{Arc, Mutex};
    struct RecordingLlm {
        inner: MockLlm,
        seen: Arc<Mutex<Vec<String>>>,
    }
    impl crate::llm::LlmBackend for RecordingLlm {
        fn model(&self) -> &str {
            "recording-mock"
        }
        fn complete(&self, request: &str) -> crate::error::Result<String> {
            self.seen.lock().unwrap().push(request.to_string());
            self.inner.complete(request)
        }
    }
    let mut sub = TestSubstrate::new();
    // TWO failures against many successes: far under tool_failure's
    // threshold, so NO analyzer flags anything and `candidates` is empty.
    // The LLM must still see the failures — that is the whole point of a
    // reflection pass, and before the tool-grain seeding it saw nothing
    // here and abstained on an empty bundle.
    for _ in 0..2 {
        sub.add_tool_call("stripe_refund", true, "cancelled_before_refund");
    }
    for _ in 0..20 {
        sub.add_tool_call("stripe_refund", false, "{\"ok\":true}");
    }
    let seen = Arc::new(Mutex::new(Vec::new()));
    let e = Engine::with_builtins().with_llm(Box::new(RecordingLlm {
        inner: MockLlm {
            discover: r#"{"recommendations":[]}"#.to_string(),
            ground: r#"{"results":[]}"#.to_string(),
            verify: r#"{"results":[]}"#.to_string(),
            enrich: r#"{"notes":[]}"#.to_string(),
        },
        seen: Arc::clone(&seen),
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let seen = seen.lock().unwrap();
    let discover = seen
        .iter()
        .find(|r| r.contains("\"op\":\"discover\""))
        .expect("DISCOVER runs even with no deterministic finding to elaborate");
    let v: serde_json::Value = serde_json::from_str(discover).unwrap();
    assert!(
        v["findings"].as_array().is_none_or(|f| f.is_empty()),
        "precondition: no analyzer flagged anything"
    );
    let tools: Vec<_> = v["evidence"]
        .as_array()
        .expect("evidence")
        .iter()
        .filter(|i| i["grain_type"] == "tool")
        .collect();
    // Under the default policy the proposer may author skills, so successful
    // calls share the tool reserve too — AFTER the failures, which keep first
    // claim on it. Both failures are in the bundle regardless.
    let failures: Vec<_> = tools.iter().filter(|t| t["text"].as_str().unwrap_or("").contains(" error:")).collect();
    assert_eq!(failures.len(), 2, "both unflagged failures reach the bundle: {tools:?}");
    assert!(tools.len() > 2, "and, with skill authoring on, so do successes");
    for t in failures {
        let text = t["text"].as_str().unwrap_or("");
        assert!(
            text.contains("cancelled_before_refund"),
            "the failure body is what makes it actionable, got {text:?}"
        );
    }
    // With skill authoring off the bundle is exactly what it was before
    // skills existed: the failures and nothing else from the tool share.
    let seen2 = Arc::new(Mutex::new(Vec::new()));
    let e2 = Engine::with_builtins()
        .with_llm(Box::new(RecordingLlm {
            inner: MockLlm {
                discover: r#"{"recommendations":[]}"#.to_string(),
                ground: r#"{"results":[]}"#.to_string(),
                verify: r#"{"results":[]}"#.to_string(),
                enrich: r#"{"notes":[]}"#.to_string(),
            },
            seen: Arc::clone(&seen2),
        }))
        .with_policy(Policy::from_json(r#"{"skills": {"enabled": false}, "plans": {"enabled": false}}"#).unwrap());
    e2.run(&mut sub.inner, &RunOptions { full_sweep: true, ..Default::default() }, 10_001).unwrap();
    let seen2 = seen2.lock().unwrap();
    let d2: serde_json::Value =
        serde_json::from_str(seen2.iter().find(|r| r.contains("\"op\":\"discover\"")).unwrap()).unwrap();
    let tools2 = d2["evidence"].as_array().unwrap().iter().filter(|i| i["grain_type"] == "tool").count();
    assert_eq!(tools2, 2, "skills and plans off: only the failures, as before");
    for t in v["evidence"].as_array().unwrap().iter().filter(|i| i["grain_type"] == "tool").filter(|t| t["text"].as_str().unwrap_or("").contains(" error:")) {
        let text = t["text"].as_str().unwrap_or("");
        assert!(text.contains("cancelled_before_refund"));
    }

}

#[cfg(unix)]
#[test]
fn external_command_analyzer_surfaces_advisory_findings() {
    use crate::analyzer::Analyzer; // for .manifest()
    use std::os::unix::fs::PermissionsExt;
    let mut sub = TestSubstrate::new();
    sub.add_fact("acme", "country", "germany");

    // A tiny analyzer: consume stdin, always emit one finding. One fixed body
    // serves both the probe (reads `id`) and analyze (reads `findings`), since
    // each reply type ignores the other's fields. Written to a space-free temp
    // path (argv is whitespace-split, like --llm-cmd).
    let script = std::env::temp_dir().join(format!("loop_ext_{}.sh", std::process::id()));
    std::fs::write(
        &script,
        "#!/bin/sh\ncat >/dev/null\nprintf '%s' '{\"id\":\"acme.ext/1\",\"title\":\"ext\",\
         \"findings\":[{\"target\":\"entity:test/acme\",\"summary\":\"external flags acme\",\
         \"severity\":\"medium\",\"evidence\":[\"deadbeef\"]}]}'\n",
    )
    .unwrap();
    std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();

    let analyzer = crate::external::CommandAnalyzer::new(script.to_str().unwrap()).unwrap();
    assert_eq!(analyzer.manifest().id, "acme.ext/1");
    assert_eq!(analyzer.manifest().trust_class, crate::manifest::TrustClass::Command);
    assert_eq!(analyzer.manifest().auto_apply, crate::manifest::AutoApplyClass::Never);

    let mut e = Engine::with_builtins();
    e.register(Box::new(analyzer));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = e.recommendations(&sub.inner, None).unwrap();

    let ext: Vec<_> = recs.iter().filter(|r| r.analyzer == "acme.ext/1").collect();
    assert_eq!(ext.len(), 1, "the external finding is surfaced");
    assert_eq!(ext[0].summary.render(), "external flags acme");
    assert_eq!(ext[0].severity, crate::model::Severity::Medium);
    assert!(!ext[0].destructive, "advisory flag, not a mutation");

    std::fs::remove_file(&script).ok();
}

#[test]
fn config_edit_toggles_analyzer_and_is_admin_gated() {
    use crate::config::AnalyzerConfigUpdate;
    let mut sub = TestSubstrate::new();
    // A contradiction under a functional relation → the contradiction sweep fires.
    sub.add_fact("acme", "deploy_target", "us-east-1");
    sub.add_fact("acme", "deploy_target", "eu-west-1");
    let e = Engine::with_builtins();

    // The analyzer id, via the read-side settings (no trait import needed).
    let cid = e
        .analyzer_settings(&sub.inner)
        .unwrap()
        .into_iter()
        .find(|s| s.id.starts_with("loop.contradiction"))
        .expect("contradiction analyzer present")
        .id;

    // Non-admin scope is denied.
    let denied = e.set_analyzer_config(
        &mut sub.inner,
        &cid,
        AnalyzerConfigUpdate { enabled: Some(false), ..Default::default() },
        &ScopeSet::of(&[Scope::Review]),
    );
    assert!(matches!(denied, Err(Error::ScopeDenied(_))), "config edit needs admin");

    // Unknown analyzer id is rejected (fail-closed).
    assert!(e
        .set_analyzer_config(
            &mut sub.inner,
            "nope.x/1",
            AnalyzerConfigUpdate::default(),
            &ScopeSet::all(),
        )
        .is_err());

    // Admin disables it; the setting flips and a run no longer surfaces it.
    e.set_analyzer_config(
        &mut sub.inner,
        &cid,
        AnalyzerConfigUpdate { enabled: Some(false), ..Default::default() },
        &ScopeSet::all(),
    )
    .unwrap();
    assert!(
        !e.analyzer_settings(&sub.inner).unwrap().iter().find(|s| s.id == cid).unwrap().enabled,
        "disabled in the effective settings"
    );
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = e.recommendations(&sub.inner, None).unwrap();
    assert!(
        recs.iter().all(|r| !r.analyzer.starts_with("loop.contradiction")),
        "the disabled analyzer produced no findings"
    );
}

#[test]
fn full_sweep_reconsiders_grains_before_the_watermark() {
    use crate::model::Origin;
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("acme", "country", "germany"); // created_at 1000

    // A plain run (no llm) advances the watermark to 10_000 — past the fact.
    Engine::with_builtins()
        .run(&mut sub.inner, &RunOptions::default(), 10_000)
        .unwrap();

    // Attach an llm that WOULD discover on that (now pre-watermark) fact.
    let discover = format!(
        r#"{{"recommendations":[{{"summary":"semantic issue on acme","target":"entity:test/acme","evidence":["{h1}"],"confidence":0.9}}]}}"#
    );
    let e = Engine::with_builtins().with_llm(Box::new(MockLlm {
        discover,
        ground: r#"{"results":[{"id":0,"supported":true}]}"#.to_string(),
        verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9}]}"#.to_string(),
        enrich: r#"{"notes":[]}"#.to_string(),
    }));

    // Incremental: discover seeds only grains since the watermark, so the old
    // fact is not in the bundle → no llm finding.
    e.run(&mut sub.inner, &RunOptions::default(), 20_000).unwrap();
    let incremental = e
        .recommendations(&sub.inner, None)
        .unwrap()
        .into_iter()
        .filter(|r| matches!(r.origin, Origin::Llm { .. }))
        .count();
    assert_eq!(incremental, 0, "an incremental run skips pre-watermark grains");

    // Full sweep: re-seeds the whole memory → the old fact is reconsidered.
    let sweep = RunOptions { full_sweep: true, ..Default::default() };
    e.run(&mut sub.inner, &sweep, 30_000).unwrap();
    let swept = e
        .recommendations(&sub.inner, None)
        .unwrap()
        .into_iter()
        .filter(|r| matches!(r.origin, Origin::Llm { .. }))
        .count();
    assert_eq!(swept, 1, "a full sweep reconsiders pre-watermark grains");
}

#[test]
fn no_llm_backend_is_the_identity() {
    use crate::model::Origin;
    let mut sub = TestSubstrate::new();
    sub.add_fact("acme", "deploy_target", "us-east-1");
    sub.add_fact("acme", "deploy_target", "eu-west-1");
    let e = Engine::with_builtins(); // no LLM attached
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    let recs = e.recommendations(&sub.inner, None).unwrap();
    assert!(
        recs.iter().all(|r| !matches!(r.origin, Origin::Llm { .. })),
        "no llm-origin recs without a backend"
    );
}

#[test]
fn review_apply_rollback_on_nondestructive() {
    let mut sub = TestSubstrate::new();
    for _ in 0..5 {
        sub.add_tool_call("stripe_refund", true, "rate_limited 429");
    }
    sub.add_tool_call("stripe_refund", false, "ok");
    let e = Engine::with_builtins();
    e.run(&mut sub.inner, &RunOptions::default(), 10_000)
        .unwrap();

    let recs = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap();
    let tf = recs
        .iter()
        .find(|r| r.analyzer.starts_with("loop.tool_failure"))
        .expect("a tool-failure recommendation");
    let hash = tf.hash.clone();
    assert!(!tf.destructive);

    let scopes = ScopeSet::all();
    e.review(
        &mut sub.inner,
        &hash,
        Decision::Approve,
        "user:alice",
        ObserverType::Human,
        &scopes,
        "retries belong in the client",
        11_000,
    )
    .unwrap();
    let applied = e
        .apply(
            &mut sub.inner,
            &hash,
            "user:alice",
            ObserverType::Human,
            &scopes,
            "applying the lesson",
            false,
            12_000,
        )
        .unwrap();
    assert!(applied.rollbackable);
    assert_eq!(
        applied.created_hashes.len(),
        1,
        "the ADD created one lesson grain"
    );
    assert_eq!(status_of(&e, &sub, &hash), RecStatus::Applied);

    e.rollback(
        &mut sub.inner,
        &hash,
        "user:alice",
        ObserverType::Human,
        &scopes,
        "undo",
        13_000,
    )
    .unwrap();
    assert_eq!(status_of(&e, &sub, &hash), RecStatus::RolledBack);
}

#[test]
fn destructive_apply_requires_admin_and_flag() {
    let mut sub = TestSubstrate::new();
    sub.add_fact_valid_to("promo", "active", "true", 500);
    let e = Engine::with_builtins();
    e.run(&mut sub.inner, &RunOptions::default(), 10_000)
        .unwrap();

    let recs = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap();
    let st = recs
        .iter()
        .find(|r| r.analyzer.starts_with("loop.staleness"))
        .expect("a staleness recommendation");
    let hash = st.hash.clone();
    assert!(st.destructive);

    let scopes = ScopeSet::all();
    e.review(
        &mut sub.inner,
        &hash,
        Decision::Approve,
        "user:alice",
        ObserverType::Human,
        &scopes,
        "expired",
        11_000,
    )
    .unwrap();

    // Without allow_destructive → gated even with admin scope.
    let denied = e.apply(
        &mut sub.inner,
        &hash,
        "user:alice",
        ObserverType::Human,
        &scopes,
        "apply",
        false,
        12_000,
    );
    assert!(matches!(denied, Err(Error::DestructiveGated(_))));

    // With allow_destructive → applies, and is non-rollbackable.
    let ok = e
        .apply(
            &mut sub.inner,
            &hash,
            "user:alice",
            ObserverType::Human,
            &scopes,
            "apply",
            true,
            12_000,
        )
        .unwrap();
    assert!(!ok.rollbackable, "FORGET has no inverse");
}

/// A PURGE in a proposal must stamp `destructive` (and so hit the
/// admin + allow_destructive apply gate) exactly like a FORGET — proposals
/// from LLM enrichment or `--analyzer-cmd` are arbitrary CAL text, and a
/// FORGET-only check would let bulk erasure ride through as "rollbackable".
#[test]
fn purge_proposal_is_stamped_destructive_and_gated() {
    use crate::analyzer::{AnalyzeCtx, Analyzer};
    use crate::manifest::{
        AnalyzerManifest, AutoApplyClass, CadenceClass, TargetClass, Tier, TrustClass,
    };
    use crate::model::ActionKind;
    use crate::recommendation::{Proposal, RecDraft, Summary};

    struct PurgeProposer {
        manifest: AnalyzerManifest,
    }
    impl Analyzer for PurgeProposer {
        fn manifest(&self) -> &AnalyzerManifest {
            &self.manifest
        }
        fn analyze(&self, _ctx: &AnalyzeCtx) -> crate::error::Result<Vec<RecDraft>> {
            Ok(vec![RecDraft::new(
                "grain:deadbeef",
                ActionKind::Expire,
                Summary::new("test.purge", serde_json::Map::new()),
                Proposal::Cal {
                    cal: r#"PURGE OLDER THAN 90d BECAUSE "retention""#.into(),
                },
            )])
        }
    }

    let mut sub = TestSubstrate::new();
    sub.add_fact("acme", "tier", "Enterprise");
    let mut e = Engine::with_builtins();
    e.register(Box::new(PurgeProposer {
        manifest: AnalyzerManifest {
            id: "test.purge/1".into(),
            title: "Purge proposer".into(),
            description: "test-only".into(),
            tier: Tier::T0,
            cadence: CadenceClass::Fast,
            requires: vec![],
            target_classes: vec![TargetClass::Memory],
            auto_apply: AutoApplyClass::Never,
            trust_class: TrustClass::Builtin,
            params: vec![],
            default_on: true,
        },
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();

    let recs = e.recommendations(&sub.inner, None).unwrap();
    let purge = recs
        .iter()
        .find(|r| r.analyzer == "test.purge/1")
        .expect("the purge recommendation");
    assert!(purge.destructive, "PURGE must stamp destructive");
    assert!(!purge.rollbackable, "bulk erasure has no inverse");

    let scopes = ScopeSet::all();
    let hash = purge.hash.clone();
    e.review(
        &mut sub.inner,
        &hash,
        Decision::Approve,
        "user:alice",
        ObserverType::Human,
        &scopes,
        "retention",
        11_000,
    )
    .unwrap();
    let denied = e.apply(
        &mut sub.inner,
        &hash,
        "user:alice",
        ObserverType::Human,
        &scopes,
        "apply",
        false,
        12_000,
    );
    assert!(
        matches!(denied, Err(Error::DestructiveGated(_))),
        "destructive gate must hold for PURGE, got {denied:?}"
    );
}

#[test]
fn apply_on_pending_is_rejected() {
    let mut sub = TestSubstrate::new();
    for _ in 0..5 {
        sub.add_tool_call("s", true, "boom 1");
    }
    let e = Engine::with_builtins();
    e.run(&mut sub.inner, &RunOptions::default(), 10_000)
        .unwrap();
    let hash = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()[0]
        .hash
        .clone();

    // pending → applied is policy-only; a human must approve first.
    let res = e.apply(
        &mut sub.inner,
        &hash,
        "user:alice",
        ObserverType::Human,
        &ScopeSet::all(),
        "x",
        false,
        11_000,
    );
    assert!(matches!(res, Err(Error::LifecycleViolation(_))));
}

#[test]
fn self_approval_blocked_against_creator() {
    let mut sub = TestSubstrate::new();
    for _ in 0..5 {
        sub.add_tool_call("s", true, "boom 1");
    }
    let e = Engine::with_builtins();
    e.run(&mut sub.inner, &RunOptions::default(), 10_000)
        .unwrap();
    let rec = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()[0]
        .clone();
    let creator = format!("engine:{}", rec.analyzer);

    let blocked = e.review(
        &mut sub.inner,
        &rec.hash,
        Decision::Approve,
        &creator,
        ObserverType::System,
        &ScopeSet::all(),
        "self",
        11_000,
    );
    assert!(matches!(blocked, Err(Error::SelfApproval(_))));

    // A different actor approves fine.
    assert!(e
        .review(
            &mut sub.inner,
            &rec.hash,
            Decision::Approve,
            "user:alice",
            ObserverType::Human,
            &ScopeSet::all(),
            "ok",
            11_000
        )
        .is_ok());
}

#[test]
fn llm_rec_blocks_approval_by_triggering_actor() {
    use crate::model::Origin;
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("acme", "deploy_target", "us-east-1");
    let _h2 = sub.add_fact("acme", "deploy_target", "eu-west-1");
    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"prod region is ambiguous","target":"entity:test/acme","guidance":"pick one","evidence":["{h1}"],"confidence":0.9}}
        ]}}"#
    );
    let ground = r#"{"results":[{"id":0,"supported":true,"reason":"entailed"}]}"#.to_string();
    let verify =
        r#"{"results":[{"id":0,"keep":true,"confidence":0.88,"reason":"real"}]}"#.to_string();
    let enrich = r#"{"notes":[]}"#.to_string();
    let e = Engine::with_builtins().with_llm(Box::new(MockLlm { discover, ground, verify, enrich }));

    let opts = RunOptions {
        triggering_actor: Some("user:sam".into()),
        ..Default::default()
    };
    e.run(&mut sub.inner, &opts, 10_000).unwrap();

    let recs = e.recommendations(&sub.inner, Some(RecStatus::Pending)).unwrap();
    let llm = recs
        .iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }))
        .expect("an llm-origin recommendation");
    let det = recs
        .iter()
        .find(|r| matches!(r.origin, Origin::Builtin))
        .expect("a deterministic recommendation");

    // The trigger of the LLM run cannot approve the model's own output —
    // the creator string is engine:loop.llm/1, so before co_creators this
    // approval sailed through.
    let blocked = e.review(
        &mut sub.inner,
        &llm.hash,
        Decision::Approve,
        "user:sam",
        ObserverType::Human,
        &ScopeSet::all(),
        "looks right to me",
        11_000,
    );
    assert!(matches!(blocked, Err(Error::SelfApproval(_))));

    // A different reviewer can.
    assert!(e
        .review(
            &mut sub.inner,
            &llm.hash,
            Decision::Approve,
            "user:review",
            ObserverType::Human,
            &ScopeSet::all(),
            "verified against the fork",
            11_000
        )
        .is_ok());

    // The deterministic finding stays approvable by the trigger — it is
    // computed, not authored, so its creator remains the engine.
    assert!(e
        .review(
            &mut sub.inner,
            &det.hash,
            Decision::Approve,
            "user:sam",
            ObserverType::Human,
            &ScopeSet::all(),
            "resolve to latest",
            11_000
        )
        .is_ok());
}

#[test]
fn review_requires_review_scope() {
    let mut sub = TestSubstrate::new();
    for _ in 0..5 {
        sub.add_tool_call("s", true, "boom 1");
    }
    let e = Engine::with_builtins();
    e.run(&mut sub.inner, &RunOptions::default(), 10_000)
        .unwrap();
    let hash = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()[0]
        .hash
        .clone();

    let write_only = ScopeSet::of(&[Scope::Read, Scope::Write]);
    let res = e.review(
        &mut sub.inner,
        &hash,
        Decision::Approve,
        "user:bob",
        ObserverType::Human,
        &write_only,
        "x",
        11_000,
    );
    assert!(matches!(res, Err(Error::ScopeDenied(_))), "write ⊉ review");
}

#[test]
fn empty_because_is_rejected() {
    let mut sub = TestSubstrate::new();
    for _ in 0..5 {
        sub.add_tool_call("s", true, "boom 1");
    }
    let e = Engine::with_builtins();
    e.run(&mut sub.inner, &RunOptions::default(), 10_000)
        .unwrap();
    let hash = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()[0]
        .hash
        .clone();

    let res = e.review(
        &mut sub.inner,
        &hash,
        Decision::Approve,
        "user:bob",
        ObserverType::Human,
        &ScopeSet::all(),
        "   ",
        11_000,
    );
    assert!(
        matches!(res, Err(Error::InvalidProposal(_))),
        "BECAUSE is mandatory"
    );
}

#[test]
fn gating_min_new_skips_but_stale_runs_first() {
    // min_new gate on a thin file skips cleanly.
    let mut sub = TestSubstrate::new();
    sub.add_fact("a", "b", "c");
    let e = Engine::with_builtins();
    let opts = RunOptions {
        min_new: Some(100),
        ..Default::default()
    };
    let r = e.run(&mut sub.inner, &opts, 10_000).unwrap();
    assert_eq!(r.outcome, RunOutcome::Skipped);
    assert_eq!(r.skip_reason, Some(SkipReason::MinNewNotMet));

    // if_stale on a never-run file runs (last_run is None).
    let mut sub2 = TestSubstrate::new();
    sub2.add_fact("a", "b", "c");
    let stale = RunOptions {
        if_stale_ms: Some(3_600_000),
        ..Default::default()
    };
    assert!(e.run(&mut sub2.inner, &stale, 10_000).unwrap().ran());
}

#[test]
fn min_new_errors_wakes_a_run() {
    let mut sub = TestSubstrate::new();
    // Two prior runs establish a watermark; then add only error events.
    let e = Engine::with_builtins();
    e.run(&mut sub.inner, &RunOptions::default(), 1_000)
        .unwrap();
    for _ in 0..4 {
        sub.add_tool_call("s", true, "boom 1");
    }
    // min_new very high (won't trip) but min_new_errors low (will).
    let opts = RunOptions {
        min_new: Some(1000),
        min_new_errors: Some(3),
        ..Default::default()
    };
    assert!(
        e.run(&mut sub.inner, &opts, 2_000).unwrap().ran(),
        "error gate wakes the run"
    );
}

#[test]
fn default_policy_auto_applies_nothing() {
    let mut sub = TestSubstrate::new();
    sub.add_fact("acme", "tier", "Enterprise");
    sub.add_fact("acme", "tier", "Enterprise");
    let e = Engine::with_builtins();
    let r = e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    assert_eq!(r.auto_applied, 0, "a closed policy applies nothing");
    assert!(e
        .recommendations(&sub.inner, None)
        .unwrap()
        .iter()
        .all(|x| x.status == RecStatus::Pending));
}

#[test]
fn policy_grant_auto_applies_structural_consolidation() {
    let mut sub = TestSubstrate::new();
    sub.add_fact("acme", "tier", "Enterprise");
    sub.add_fact("acme", "tier", "Enterprise"); // exact dup → SUPERSEDE-only proposal
    let policy = Policy::from_json(
        r#"{"auto_apply_enabled": true,
            "auto_apply": [{"analyzer": "loop.duplicate_sweep", "targets": ["memory"], "max_severity": "low"}]}"#,
    )
    .unwrap();
    let e = Engine::with_builtins().with_policy(policy);
    let r = e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    assert_eq!(r.auto_applied, 1, "the consolidation is auto-applied");
    let applied = e.recommendations(&sub.inner, Some(RecStatus::Applied)).unwrap();
    assert_eq!(applied.len(), 1);
    assert!(applied[0].analyzer.starts_with("loop.duplicate_sweep"));
}

#[test]
fn fork_merge_never_auto_applies_even_when_granted() {
    let mut sub = TestSubstrate::new();
    sub.add_fork("caller/john", &["ref-a", "ref-b"]);
    // A merge is SUPERSEDE-only (passes the shape check), but it is lossy, so
    // its manifest is Never — even an explicit policy grant cannot auto-apply it.
    let policy = Policy::from_json(
        r#"{"auto_apply_enabled": true,
            "auto_apply": [{"analyzer": "loop.fork_surfacing", "targets": ["memory"], "max_severity": "high"}]}"#,
    )
    .unwrap();
    let e = Engine::with_builtins().with_policy(policy);
    let r = e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    assert_eq!(r.auto_applied, 0, "a lossy fork merge is never auto-applied");
    assert!(
        e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .iter()
            .any(|x| x.analyzer.starts_with("loop.fork_surfacing")),
        "it is proposed for human review instead"
    );
}

#[test]
fn auto_apply_never_touches_free_text_add() {
    // tool-failure proposes an ADD carrying an evidence-derived signature —
    // shape verification rejects it even when the policy names it.
    let mut sub = TestSubstrate::new();
    for _ in 0..5 {
        sub.add_tool_call("s", true, "boom 1");
    }
    let policy = Policy::from_json(
        r#"{"auto_apply_enabled": true,
            "auto_apply": [{"analyzer": "loop.tool_failure", "targets": ["memory"], "max_severity": "high"}]}"#,
    )
    .unwrap();
    let e = Engine::with_builtins().with_policy(policy);
    let r = e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    assert_eq!(r.auto_applied, 0, "an ADD-with-text proposal never auto-applies");
}

/// The exact-equality half of the shape check (§6.3): a near-duplicate
/// consolidation rewrites an observation body, so it must stay pending even
/// under a policy grant — while an exact (value-identical) consolidation in
/// the same run auto-applies. This is the module-doc promise of
/// `duplicate_sweep`, enforced engine-side.
#[test]
fn near_duplicate_consolidation_never_auto_applies() {
    let mut sub = TestSubstrate::new();
    sub.add_fact("acme", "tier", "Enterprise");
    sub.add_fact("acme", "tier", "enterprise"); // exact (case variant)
    sub.add_observation("caller", "user asked about pricing tiers refunds billing invoices today");
    sub.add_observation(
        "caller",
        "user asked about pricing tiers refunds billing invoices today please", // near, not exact
    );
    let policy = Policy::from_json(
        r#"{"auto_apply_enabled": true,
            "auto_apply": [{"analyzer": "loop.duplicate_sweep", "targets": ["memory"], "max_severity": "low"}]}"#,
    )
    .unwrap();
    let e = Engine::with_builtins().with_policy(policy);
    let r = e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    assert_eq!(r.auto_applied, 1, "only the value-identical consolidation auto-applies");
    let recs = e.recommendations(&sub.inner, None).unwrap();
    let near = recs
        .iter()
        .find(|x| x.summary.template_id == "duplicate.near")
        .expect("the near-dup consolidation is proposed");
    assert_eq!(
        near.status,
        RecStatus::Pending,
        "a body-rewriting consolidation waits for a human"
    );
}

/// An auto-applied consolidation must keep the fact in its namespace — the
/// replacement grain carries `namespace`, so ns-scoped recall still finds the
/// value afterwards.
#[test]
fn auto_applied_consolidation_preserves_namespace() {
    use crate::substrate::{ReadOpts, SubstrateRead};
    let mut sub = TestSubstrate::new();
    sub.add_fact("acme", "tier", "Enterprise");
    sub.add_fact("acme", "tier", "Enterprise");
    let policy = Policy::from_json(
        r#"{"auto_apply_enabled": true,
            "auto_apply": [{"analyzer": "loop.duplicate_sweep", "targets": ["memory"], "max_severity": "low"}]}"#,
    )
    .unwrap();
    let e = Engine::with_builtins().with_policy(policy);
    let r = e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    assert_eq!(r.auto_applied, 1);
    let live = sub
        .inner
        .grains_of_type("fact", None, ReadOpts { live_only: true, since_ms: None })
        .unwrap();
    let acme: Vec<_> = live
        .iter()
        .filter(|g| g.fact_subject() == Some("acme"))
        .collect();
    assert!(!acme.is_empty());
    assert!(
        acme.iter().all(|g| g.namespace == "test"),
        "no replacement grain escaped to the store default namespace"
    );
}

/// An applied tool-failure lesson lands in the namespace of its evidence, so
/// the ns-scoped recall the agent actually runs can surface it.
#[test]
fn applied_lesson_lands_in_evidence_namespace() {
    let mut sub = TestSubstrate::new();
    for _ in 0..5 {
        sub.add_tool_call("stripe_refund", true, "rate_limited 429");
    }
    sub.add_tool_call("stripe_refund", false, "ok");
    let e = Engine::with_builtins();
    e.run(&mut sub.inner, &RunOptions::default(), 1_000_000).unwrap();
    let hash = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| r.analyzer.starts_with("loop.tool_failure"))
        .expect("a tool-failure lesson")
        .hash;
    let scopes = ScopeSet::all();
    e.review(&mut sub.inner, &hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "codify", 1_000_100).unwrap();
    let applied = e
        .apply(&mut sub.inner, &hash, "user:a", ObserverType::Human, &scopes, "apply", false, 1_000_200)
        .unwrap();
    let created = applied.created_hashes.first().expect("the lesson grain");
    use crate::substrate::SubstrateRead;
    let grain = sub.inner.grain(created).unwrap().expect("stored");
    assert_eq!(
        grain.namespace, "test",
        "the lesson inherits the evidence tool calls' namespace"
    );
}

#[test]
fn policy_deny_disables_an_analyzer() {
    let mut sub = TestSubstrate::new();
    sub.add_fact("acme", "tier", "Enterprise");
    sub.add_fact("acme", "tier", "Enterprise");
    let policy = Policy::from_json(r#"{"deny": ["loop.duplicate_sweep"]}"#).unwrap();
    let e = Engine::with_builtins().with_policy(policy);
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    assert!(
        e.recommendations(&sub.inner, None)
            .unwrap()
            .iter()
            .all(|x| !x.analyzer.starts_with("loop.duplicate_sweep")),
        "a denied analyzer produces nothing"
    );
}

const DAY: i64 = 86_400_000;

/// Apply a tool-failure lesson; return (engine, sub, rec_hash) at apply time T.
fn apply_lesson(now: i64) -> (Engine, TestSubstrate, String) {
    let mut sub = TestSubstrate::new();
    for _ in 0..5 {
        sub.add_tool_call_at("stripe_refund", true, "rate_limited 429", 1_000);
    }
    sub.add_tool_call_at("stripe_refund", false, "ok", 1_100);
    let e = Engine::with_builtins();
    e.run(&mut sub.inner, &RunOptions::default(), 1_000_000).unwrap();
    let hash = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| r.analyzer.starts_with("loop.tool_failure"))
        .expect("a tool-failure lesson")
        .hash;
    let scopes = ScopeSet::all();
    e.review(&mut sub.inner, &hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "codify", now).unwrap();
    e.apply(&mut sub.inner, &hash, "user:a", ObserverType::Human, &scopes, "apply the rule", false, now).unwrap();
    (e, sub, hash)
}

/// The multi-horizon Verify gate: a LATE recurrence that early checkpoints miss
/// is caught at a later one — held at 1d, held at 7d, regressed at 30d.
#[test]
fn outcome_time_series_catches_a_late_regression() {
    let t = 2_000_000;
    let (e, mut sub, hash) = apply_lesson(t);

    // Measure the 1d and 7d checkpoints — no recurrence yet.
    e.run(&mut sub.inner, &RunOptions::default(), t + 2 * DAY).unwrap();
    e.run(&mut sub.inner, &RunOptions::default(), t + 8 * DAY).unwrap();

    // The failure recurs at day 20 — after the early checkpoints.
    for _ in 0..2 {
        sub.add_tool_call_at("stripe_refund", true, "rate_limited 429", t + 20 * DAY);
    }

    // Measure the 30d checkpoint.
    e.run(&mut sub.inner, &RunOptions::default(), t + 31 * DAY).unwrap();

    let series: Vec<_> = e
        .outcomes(&sub.inner)
        .unwrap()
        .into_iter()
        .filter(|o| o.rec_hash == hash)
        .collect();
    let verdict_at = |h: i64| series.iter().find(|o| o.horizon_ms == h).map(|o| o.verdict.as_str());
    assert_eq!(verdict_at(DAY), Some("held"), "no recurrence at day 1");
    assert_eq!(verdict_at(7 * DAY), Some("held"), "still held at day 7");
    assert_eq!(verdict_at(30 * DAY), Some("regressed"), "the late recurrence is caught at day 30");
    assert!(
        e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .iter()
            .any(|r| r.analyzer.starts_with("loop.outcome_review")),
        "a revert is proposed once the regression appears"
    );

    // The regression recommendation is not merely an audit transition: apply
    // it and prove the original lesson grain is retracted through the same
    // rollback path as a direct human rollback.
    use crate::substrate::{ReadOpts, SubstrateRead};
    let lesson = sub
        .inner
        .grains_of_type("fact", Some("test"), ReadOpts::default())
        .unwrap()
        .into_iter()
        .find(|g| {
            g.fields.get("subject").and_then(serde_json::Value::as_str)
                == Some("stripe_refund")
                && g.fields.get("relation").and_then(serde_json::Value::as_str)
                    == Some("fails_with")
        })
        .expect("applied lesson grain");
    let revert = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| r.analyzer.starts_with("loop.outcome_review"))
        .expect("revert recommendation");
    let scopes = ScopeSet::all();
    e.review(
        &mut sub.inner,
        &revert.hash,
        Decision::Approve,
        "user:a",
        ObserverType::Human,
        &scopes,
        "regression confirmed",
        t + 31 * DAY + 1,
    )
    .unwrap();
    e.apply(
        &mut sub.inner,
        &revert.hash,
        "user:a",
        ObserverType::Human,
        &scopes,
        "revert regressed lesson",
        false,
        t + 31 * DAY + 2,
    )
    .unwrap();
    assert_eq!(status_of(&e, &sub, &hash), RecStatus::RolledBack);
    assert_eq!(status_of(&e, &sub, &revert.hash), RecStatus::Applied);
    assert!(
        !sub.inner.grain(&lesson.hash).unwrap().unwrap().is_live(),
        "the lesson created by the original apply must be retracted"
    );
}

/// A revert the Verify gate proposed is a verdict on the FINDING: once a
/// reviewer applies it, the reverted lesson goes on the rejection cooldown
/// and the next pass does not re-propose it — even though the failure
/// cluster that produced it is still there. An operator's own rollback earns
/// no cooldown, so the same cluster re-proposes the same lesson at once.
/// Both arms share every input up to the rollback mechanism, which is what
/// makes the difference attributable to it.
#[test]
fn a_measured_revert_cools_down_the_reverted_finding_but_a_manual_rollback_does_not() {
    use crate::substrate::OmsSubstrate;
    let t = 2_000_000;
    let scopes = ScopeSet::all();
    let cooldown_of = |sub: &TestSubstrate, dk: &str| -> Option<i64> {
        crate::config::LoopPersisted::from_value(sub.inner.load_state().unwrap())
            .unwrap()
            .cooldowns
            .get(dk)
            .copied()
    };
    let pending_lesson = |e: &Engine, sub: &TestSubstrate, dk: &str| -> bool {
        e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .iter()
            .any(|r| r.analyzer.starts_with("loop.tool_failure") && r.dedup_key == dk)
    };
    // Shared prefix: apply the lesson, pass the early checkpoints, then the
    // failure comes back in force — enough for the analyzer to fire again on
    // its own, not only for the recurrence metric to regress.
    let regress = |now: i64| -> (Engine, TestSubstrate, String, String) {
        let (e, mut sub, hash) = apply_lesson(now);
        let dk = load_dedup_key(&e, &sub, &hash);
        e.run(&mut sub.inner, &RunOptions::default(), now + 2 * DAY).unwrap();
        e.run(&mut sub.inner, &RunOptions::default(), now + 8 * DAY).unwrap();
        for _ in 0..5 {
            sub.add_tool_call_at("stripe_refund", true, "rate_limited 429", now + 30 * DAY);
        }
        sub.add_tool_call_at("stripe_refund", false, "ok", now + 30 * DAY + 1);
        e.run(&mut sub.inner, &RunOptions::default(), now + 31 * DAY).unwrap();
        (e, sub, hash, dk)
    };

    // Arm 1 — the Verify gate's revert, approved and applied.
    let (e, mut sub, hash, dk) = regress(t);
    let revert = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| r.analyzer.starts_with("loop.outcome_review"))
        .expect("the regression proposed a revert");
    assert!(cooldown_of(&sub, &dk).is_none(), "no cooldown before the revert");
    e.review(&mut sub.inner, &revert.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "regression confirmed", t + 31 * DAY + 1)
        .unwrap();
    let applied_at = t + 31 * DAY + 2;
    e.apply(&mut sub.inner, &revert.hash, "user:a", ObserverType::Human, &scopes, "revert regressed lesson", false, applied_at)
        .unwrap();
    assert_eq!(status_of(&e, &sub, &hash), RecStatus::RolledBack);
    assert_eq!(
        cooldown_of(&sub, &dk),
        Some(applied_at + 7 * DAY),
        "a measured revert earns the reverted finding a first-strike (7d) cooldown"
    );
    e.run(&mut sub.inner, &RunOptions::default(), applied_at + 1).unwrap();
    assert!(
        !pending_lesson(&e, &sub, &dk),
        "the lesson the gate just retracted must not be re-proposed on the next pass"
    );
    // ...and once the cooldown lapses the situation is judged afresh.
    e.run(&mut sub.inner, &RunOptions::default(), applied_at + 7 * DAY + 1).unwrap();
    assert!(
        pending_lesson(&e, &sub, &dk),
        "after the cooldown the still-present cluster re-proposes the lesson"
    );

    // Arm 2 — the same state, rolled back by an operator instead.
    let (e, mut sub, hash, dk) = regress(t);
    let rolled_at = t + 31 * DAY + 2;
    e.rollback(&mut sub.inner, &hash, "user:a", ObserverType::Human, &scopes, "retract it by hand", rolled_at)
        .unwrap();
    assert_eq!(status_of(&e, &sub, &hash), RecStatus::RolledBack);
    assert!(cooldown_of(&sub, &dk).is_none(), "an operator rollback earns no cooldown");
    e.run(&mut sub.inner, &RunOptions::default(), rolled_at + 1).unwrap();
    assert!(
        pending_lesson(&e, &sub, &dk),
        "after a manual rollback the still-present cluster re-proposes the lesson at once"
    );
}

fn load_dedup_key(e: &Engine, sub: &TestSubstrate, hash: &str) -> String {
    e.recommendations(&sub.inner, None)
        .unwrap()
        .into_iter()
        .find(|r| r.hash == hash)
        .expect("the applied recommendation is listed")
        .dedup_key
}

/// No recurrence at any checkpoint → the fix held across the whole series, no
/// revert ever proposed.
#[test]
fn outcome_time_series_holds_when_fix_works() {
    let t = 2_000_000;
    let (e, mut sub, hash) = apply_lesson(t);
    sub.add_tool_call_at("stripe_refund", false, "ok", t + 10 * DAY); // only a success
    e.run(&mut sub.inner, &RunOptions::default(), t + 31 * DAY).unwrap();

    let series: Vec<_> = e
        .outcomes(&sub.inner)
        .unwrap()
        .into_iter()
        .filter(|o| o.rec_hash == hash)
        .collect();
    assert_eq!(series.len(), 3, "all three checkpoints measured");
    assert!(series.iter().all(|o| o.verdict == "held"), "held throughout");
    assert!(
        !e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .iter()
            .any(|r| r.analyzer.starts_with("loop.outcome_review")),
        "no revert when the fix held"
    );
}

/// Apply a contradiction resolution; return (engine, sub, rec_hash).
fn apply_resolution(now: i64) -> (Engine, TestSubstrate, String) {
    let mut sub = TestSubstrate::new();
    sub.add_fact("acme", "deploy_target", "us-east-1");
    sub.add_fact("acme", "deploy_target", "eu-west-1");
    let e = Engine::with_builtins();
    e.run(&mut sub.inner, &RunOptions::default(), 1_000_000).unwrap();
    let hash = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| r.analyzer.starts_with("loop.contradiction_sweep"))
        .expect("a contradiction resolution")
        .hash;
    let scopes = ScopeSet::all();
    e.review(&mut sub.inner, &hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "latest wins", now).unwrap();
    e.apply(&mut sub.inner, &hash, "user:a", ObserverType::Human, &scopes, "resolve", false, now).unwrap();
    (e, sub, hash)
}

/// The contradiction-recurrence metric: held while the subject keeps one live
/// value; a NEW conflicting value after apply regresses a later checkpoint and
/// a revert is proposed — the Verify gate now covers resolutions, not just
/// tool lessons.
#[test]
fn contradiction_outcome_regresses_when_conflict_returns() {
    let t = 2_000_000;
    let (e, mut sub, hash) = apply_resolution(t);

    // 1d checkpoint: resolved — one live value → held.
    e.run(&mut sub.inner, &RunOptions::default(), t + 2 * DAY).unwrap();

    // A new conflicting value arrives after the early checkpoint.
    sub.add_fact("acme", "deploy_target", "ap-south-1");

    // 7d checkpoint: two live values again → regressed.
    e.run(&mut sub.inner, &RunOptions::default(), t + 8 * DAY).unwrap();

    let series: Vec<_> = e
        .outcomes(&sub.inner)
        .unwrap()
        .into_iter()
        .filter(|o| o.rec_hash == hash)
        .collect();
    let verdict_at = |h: i64| series.iter().find(|o| o.horizon_ms == h).map(|o| o.verdict.as_str());
    assert_eq!(verdict_at(DAY), Some("held"), "one live value at day 1");
    assert_eq!(verdict_at(7 * DAY), Some("regressed"), "the returned conflict is caught at day 7");
    assert!(
        e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .iter()
            .any(|r| r.analyzer.starts_with("loop.outcome_review")),
        "a revert is proposed for the regressed resolution"
    );
}

#[test]
fn contradiction_outcome_holds_when_resolution_sticks() {
    let t = 2_000_000;
    let (e, mut sub, hash) = apply_resolution(t);
    e.run(&mut sub.inner, &RunOptions::default(), t + 31 * DAY).unwrap();
    let series: Vec<_> = e
        .outcomes(&sub.inner)
        .unwrap()
        .into_iter()
        .filter(|o| o.rec_hash == hash)
        .collect();
    assert_eq!(series.len(), 3, "all three checkpoints measured");
    assert!(series.iter().all(|o| o.verdict == "held"), "held throughout");
}

fn status_of(e: &Engine, sub: &TestSubstrate, hash: &str) -> RecStatus {
    e.recommendations(&sub.inner, None)
        .unwrap()
        .into_iter()
        .find(|r| r.hash == hash)
        .unwrap()
        .status
}

// ── Regression: mechanism-traced findings fixed 2026-07-25 ──────────────────

/// #A6F1 — a tool lesson's outcome metric is scoped to its failure signature;
/// an unrelated later failure of the SAME tool must not read as a regression.
#[test]
fn tool_lesson_holds_on_unrelated_same_tool_failure() {
    let t = 2_000_000;
    let (e, mut sub, hash) = apply_lesson(t); // lesson signature = "rate_limited #"
    // A different-signature failure of the same tool, after the apply.
    for _ in 0..3 {
        sub.add_tool_call_at("stripe_refund", true, "insufficient_funds 402", t + 2 * DAY);
    }
    e.run(&mut sub.inner, &RunOptions::default(), t + 31 * DAY).unwrap();
    let series: Vec<_> = e
        .outcomes(&sub.inner)
        .unwrap()
        .into_iter()
        .filter(|o| o.rec_hash == hash)
        .collect();
    assert!(!series.is_empty(), "the metric was measured");
    assert!(
        series.iter().all(|o| o.verdict == "held"),
        "an unrelated-signature failure must not regress the lesson: {:?}",
        series.iter().map(|o| (o.horizon_ms, o.verdict.clone())).collect::<Vec<_>>()
    );
    assert!(
        !e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .iter()
            .any(|r| r.analyzer.starts_with("loop.outcome_review")),
        "no revert proposed for an unrelated failure"
    );
}

/// #A6F2 — the value-identical auto-apply gate fails closed when the superseded
/// grain carries information the {s,r,o,ns} replacement can't preserve.
#[test]
fn auto_apply_blocks_dropped_expiry() {
    let mut sub = TestSubstrate::new();
    sub.add_fact("acme", "tier", "Enterprise"); // canonical (earliest)
    sub.add_fact_valid_to("acme", "tier", "Enterprise", 999_999); // dup WITH an expiry
    let policy = Policy::from_json(
        r#"{"auto_apply_enabled": true,
            "auto_apply": [{"analyzer": "loop.duplicate_sweep", "targets": ["memory"], "max_severity": "low"}]}"#,
    )
    .unwrap();
    let e = Engine::with_builtins().with_policy(policy);
    let r = e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    assert_eq!(r.auto_applied, 0, "a dup carrying a valid_to must not auto-apply (expiry would be lost)");
    assert!(
        e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .iter()
            .any(|r| r.analyzer.starts_with("loop.duplicate_sweep")),
        "it stays pending for human review"
    );
}

/// A bare-value duplicate (only s/r/o/ns, no expiry) still auto-applies — the
/// narrowed A6F2 guard must not block legitimate consolidation.
#[test]
fn auto_apply_still_consolidates_plain_duplicates() {
    let mut sub = TestSubstrate::new();
    sub.add_fact("acme", "tier", "Enterprise");
    sub.add_fact("acme", "tier", "Enterprise");
    let policy = Policy::from_json(
        r#"{"auto_apply_enabled": true,
            "auto_apply": [{"analyzer": "loop.duplicate_sweep", "targets": ["memory"], "max_severity": "low"}]}"#,
    )
    .unwrap();
    let e = Engine::with_builtins().with_policy(policy);
    let r = e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();
    assert_eq!(r.auto_applied, 1, "plain value-identical duplicates still consolidate");
}

/// #A6F4 — an empty/whitespace error signature yields no (unappliable) lesson.
#[test]
fn empty_signature_cluster_not_proposed() {
    let mut sub = TestSubstrate::new();
    for _ in 0..6 {
        sub.add_tool_call("flaky", true, "   "); // whitespace-only error body → sig ""
    }
    let drafts = sub.analyze(&crate::analyzers::tool_failure::ToolFailureClustering::new(), 10_000);
    assert!(drafts.is_empty(), "an empty-signature cluster must not be proposed, got {}", drafts.len());
}

/// #A6F3 — rejection cooldown backs off exponentially (7d → 14d), not a flat 7d.
#[test]
fn rejection_cooldown_doubles() {
    let e = Engine::with_builtins();
    let scopes = ScopeSet::all();
    let reject_at = |sub: &mut TestSubstrate, now: i64| -> String {
        e.run(&mut sub.inner, &RunOptions::default(), now).unwrap();
        let rec = e
            .recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .into_iter()
            .find(|r| r.analyzer.starts_with("loop.contradiction"))
            .expect("a contradiction recommendation");
        let dk = rec.dedup_key.clone();
        e.review(&mut sub.inner, &rec.hash, Decision::Reject, "user:a", ObserverType::Human, &scopes, "no", now)
            .unwrap();
        dk
    };
    let mut sub = TestSubstrate::new();
    sub.add_fact("acme", "deploy_target", "us-east-1");
    sub.add_fact("acme", "deploy_target", "eu-west-1"); // contradiction
    let t0 = 10_000;
    let dk = reject_at(&mut sub, t0);
    let cooldown = |sub: &TestSubstrate, dk: &str| -> i64 {
        use crate::substrate::OmsSubstrate;
        crate::config::LoopPersisted::from_value(sub.inner.load_state().unwrap())
            .unwrap()
            .cooldowns
            .get(dk)
            .copied()
            .unwrap()
    };
    assert_eq!(cooldown(&sub, &dk) - t0, 7 * DAY, "first rejection = 7d");
    // Re-propose after the first cooldown elapses, reject again.
    let t1 = cooldown(&sub, &dk) + 1;
    reject_at(&mut sub, t1);
    assert_eq!(cooldown(&sub, &dk) - t1, 14 * DAY, "second rejection doubles to 14d");
}

#[test]
fn advisory_findings_are_refused_by_preflight_not_after_approval() {
    use crate::engine::ensure_executable;
    use crate::model::Origin;
    use crate::recommendation::Proposal;
    use serde_json::{json, Map};

    // The shared gate, pinned directly: exactly one Data shape is executable.
    use crate::model::ActionKind as AK;
    assert!(ensure_executable(AK::Flag, &Proposal::Cal { cal: "ADD fact …".into() }).is_ok());
    assert!(matches!(
        ensure_executable(AK::Flag, &Proposal::Edit {
            format: "md".into(),
            base_digest: "d".into(),
            diff: "-a\n+b".into(),
        }),
        Err(Error::InvalidProposal(_))
    ));
    let mut advisory = Map::new();
    advisory.insert("note".into(), json!("go look at this"));
    assert!(matches!(
        ensure_executable(AK::Flag, &Proposal::Data { data: advisory }),
        Err(Error::InvalidProposal(_))
    ));
    let mut revert = Map::new();
    revert.insert("revert_of".into(), json!("abc123"));
    assert!(ensure_executable(AK::Revert, &Proposal::Data { data: revert }).is_ok());
    // The gated revisions are executable Data shapes — the promotion write.
    assert!(ensure_executable(AK::CodeRevision, &Proposal::Data { data: Map::new() }).is_ok());
    assert!(ensure_executable(AK::AdapterRevision, &Proposal::Data { data: Map::new() }).is_ok());

    // End to end: an LLM finding is advisory, and preflight refuses it *before*
    // the fused approve-and-apply path commits an approval it cannot undo.
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("acme", "deploy_target", "us-east-1");
    let _h2 = sub.add_fact("acme", "deploy_target", "eu-west-1");
    let discover = format!(
        r#"{{"recommendations":[
          {{"summary":"prod region is ambiguous","target":"entity:test/acme","guidance":"pick one","evidence":["{h1}"],"confidence":0.9}}
        ]}}"#
    );
    let e = Engine::with_builtins().with_llm(Box::new(MockLlm {
        discover,
        ground: r#"{"results":[{"id":0,"supported":true,"reason":"entailed"}]}"#.into(),
        verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.88,"reason":"real"}]}"#.into(),
        enrich: r#"{"notes":[]}"#.into(),
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();

    let llm = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }))
        .expect("an llm-origin recommendation");

    let refused = e.preflight_apply(&sub.inner, &llm.hash, &ScopeSet::all(), true, false);
    assert!(
        matches!(refused, Err(Error::InvalidProposal(_))),
        "preflight must refuse an advisory finding, got {refused:?}"
    );
    assert_eq!(
        status_of(&e, &sub, &llm.hash),
        RecStatus::Pending,
        "a refused preflight must leave the finding dismissible"
    );

    // Approving it stays legal — a Flag is acknowledged, not executed.
    e.review(
        &mut sub.inner,
        &llm.hash,
        Decision::Approve,
        "user:reviewer",
        ObserverType::Human,
        &ScopeSet::all(),
        "real issue, handling it in the host",
        11_000,
    )
    .expect("acknowledging an advisory finding is legal");

    // But applying it still refuses, with guidance rather than a bare error.
    match e.apply(
        &mut sub.inner,
        &llm.hash,
        "user:reviewer",
        ObserverType::Human,
        &ScopeSet::all(),
        "try to apply",
        true,
        12_000,
    ) {
        Err(Error::InvalidProposal(msg)) => {
            assert!(msg.contains("advisory"), "message should explain, got {msg:?}")
        }
        other => panic!("expected an advisory refusal, got {other:?}"),
    }
}

/// §7.4 end-to-end (the Wave-4 gate): a code revision proposed by an
/// analyzer, reviewed by a human, REFUSED without the evalset-run edge,
/// refused with mismatched/stale/failing gates, applied only through
/// `apply_gated` with the pin live and the gate clean — and the audit
/// Observation carries the recorded edge.
#[test]
fn governed_code_change_applies_only_through_the_gate() {
    use crate::analyzer::{AnalyzeCtx, Analyzer};
    use crate::manifest::{
        AnalyzerManifest, AutoApplyClass, CadenceClass, TargetClass, Tier, TrustClass,
    };
    use crate::model::ActionKind;
    use crate::recommendation::{GatingEvidence, Proposal, RecDraft, Summary};

    struct CodeProposer {
        manifest: AnalyzerManifest,
        evalset: String,
    }
    impl Analyzer for CodeProposer {
        fn manifest(&self) -> &AnalyzerManifest {
            &self.manifest
        }
        fn analyze(&self, _ctx: &AnalyzeCtx) -> crate::error::Result<Vec<RecDraft>> {
            let mut args = serde_json::Map::new();
            args.insert("text".into(), serde_json::Value::from("faster retry backoff"));
            let mut data = serde_json::Map::new();
            data.insert("code_blob".into(), serde_json::Value::from("cas://sha256:feed"));
            Ok(vec![RecDraft::new(
                "tool:cafe0123",
                ActionKind::CodeRevision,
                Summary::new("command.finding", args),
                Proposal::Data { data },
            )
            .evalset_hash(self.evalset.clone())])
        }
    }

    let mut sub = TestSubstrate::new();
    // The evalset is itself a grain — the pin's liveness is checked at apply.
    let evalset_hash = sub.add_fact("evalset:retry", "mg:evalset", "{\"cases\":[]}");
    let mut e = Engine::with_builtins();
    e.register(Box::new(CodeProposer {
        manifest: AnalyzerManifest {
            id: "test.codegen/1".into(),
            title: "Code proposer".into(),
            description: "test-only".into(),
            tier: Tier::T0,
            cadence: CadenceClass::Fast,
            requires: vec![],
            target_classes: vec![TargetClass::Host],
            auto_apply: AutoApplyClass::Never,
            trust_class: TrustClass::Builtin,
            params: vec![],
            default_on: true,
        },
        evalset: evalset_hash.clone(),
    }));
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();

    let rec = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| r.action_kind == ActionKind::CodeRevision)
        .expect("the code revision");
    assert_eq!(rec.evalset_hash.as_deref(), Some(evalset_hash.as_str()));
    let hash = rec.hash.clone();
    let scopes = ScopeSet::all();
    e.review(
        &mut sub.inner, &hash, Decision::Approve, "user:reviewer",
        ObserverType::Human, &scopes, "diff reviewed", 11_000,
    )
    .unwrap();

    // 1. Plain apply — no gating edge — REFUSED.
    match e.apply(&mut sub.inner, &hash, "user:reviewer", ObserverType::Human, &scopes, "ship it", false, 12_000) {
        Err(Error::InvalidProposal(m)) => assert!(m.contains("gating run"), "{m}"),
        other => panic!("ungated apply must refuse, got {other:?}"),
    }
    // 2. Gated against the WRONG evalset — refused (Rule E1's pin).
    let wrong = GatingEvidence { evalset_hash: "not-the-pin".into(), run_id: "eval-1".into(), passed: 3, failed: 0 };
    match e.apply_gated(&mut sub.inner, &hash, "user:reviewer", ObserverType::Human, &scopes, "ship", false, &wrong, 12_100) {
        Err(Error::InvalidProposal(m)) => assert!(m.contains("pinned"), "{m}"),
        other => panic!("wrong-evalset apply must refuse, got {other:?}"),
    }
    // 3. A FAILING gate admits nothing.
    let failing = GatingEvidence { evalset_hash: evalset_hash.clone(), run_id: "eval-2".into(), passed: 2, failed: 1 };
    match e.apply_gated(&mut sub.inner, &hash, "user:reviewer", ObserverType::Human, &scopes, "ship", false, &failing, 12_200) {
        Err(Error::InvalidProposal(m)) => assert!(m.contains("failing gate"), "{m}"),
        other => panic!("failing-gate apply must refuse, got {other:?}"),
    }
    // 4. Clean gate, live pin: the ONLY path that applies — and the audit
    // Observation records the edge.
    let clean = GatingEvidence { evalset_hash: evalset_hash.clone(), run_id: "eval-3".into(), passed: 3, failed: 0 };
    e.apply_gated(&mut sub.inner, &hash, "user:reviewer", ObserverType::Human, &scopes, "gated and green", false, &clean, 12_300)
        .unwrap();
    let audits = {
        use crate::substrate::SubstrateRead;
        sub.inner
            .grains_of_type("observation", Some("areev-loop"), Default::default())
            .unwrap()
    };
    let applied_audit = audits
        .iter()
        .find(|a| {
            a.str_field("rec_hash") == Some(hash.as_str())
                && a.str_field("to_status") == Some("applied")
        })
        .expect("the applied audit record");
    assert_eq!(applied_audit.str_field("gating_evalset"), Some(evalset_hash.as_str()));
    assert_eq!(applied_audit.str_field("gating_run_id"), Some("eval-3"));

    // 5. Superseding the evalset AFTER apply invalidates FUTURE pins: a
    // second code rec pinned to the old evalset re-gates.
    e.run(&mut sub.inner, &RunOptions::default(), 20_000).unwrap(); // dedup: no new rec
    {
        use crate::substrate::{GrainSpec, OmsSubstrate};
        let spec = GrainSpec::new("fact", "test")
            .with_field("subject", "evalset:retry")
            .with_field("relation", "mg:evalset")
            .with_field("object", "{\"cases\":[1]}");
        sub.inner
            .supersede(&evalset_hash, &spec, "evalset v2")
            .unwrap();
    }
    // Fresh engine+proposer so a new pending rec pinned to the OLD hash exists.
    let mut e2 = Engine::with_builtins();
    e2.register(Box::new(CodeProposer {
        manifest: AnalyzerManifest {
            id: "test.codegen2/1".into(),
            title: "Code proposer 2".into(),
            description: "test-only".into(),
            tier: Tier::T0,
            cadence: CadenceClass::Fast,
            requires: vec![],
            target_classes: vec![TargetClass::Host],
            auto_apply: AutoApplyClass::Never,
            trust_class: TrustClass::Builtin,
            params: vec![],
            default_on: true,
        },
        evalset: evalset_hash.clone(),
    }));
    e2.run(&mut sub.inner, &RunOptions::default(), 21_000).unwrap();
    let rec2 = e2
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| r.action_kind == ActionKind::CodeRevision && r.analyzer.starts_with("test.codegen2"))
        .expect("second code revision");
    e2.review(&mut sub.inner, &rec2.hash, Decision::Approve, "user:reviewer", ObserverType::Human, &scopes, "ok", 22_000).unwrap();
    let stale = GatingEvidence { evalset_hash: evalset_hash.clone(), run_id: "eval-4".into(), passed: 3, failed: 0 };
    match e2.apply_gated(&mut sub.inner, &rec2.hash, "user:reviewer", ObserverType::Human, &scopes, "ship", false, &stale, 23_000) {
        Err(Error::InvalidProposal(m)) => assert!(m.contains("superseded"), "{m}"),
        other => panic!("stale-pin apply must refuse (re-gate), got {other:?}"),
    }
}

/// The tuning seam end-to-end: an `mg:adapter` registry grain (what
/// `areev tune` writes) is picked up by the builtin `adapter_intake`
/// analyzer, gated exactly like a code revision (refused ungated /
/// mismatched / failing), applied only through a clean recorded run of the
/// pinned evalset — writing the `mg:adapter_promotion` Fact hosts re-resolve
/// from — and rolled back by retracting it, after which the candidate is
/// re-proposed (the situation returned) until its registry grain is retired.
#[test]
fn governed_adapter_promotion_applies_only_through_the_gate() {
    use crate::model::ActionKind;
    use crate::recommendation::GatingEvidence;

    let mut sub = TestSubstrate::new();
    let evalset_hash = sub.add_fact("evalset:support", "mg:evalset", "{\"cases\":[]}");
    let tuple = serde_json::json!({
        "adapter": {"uri": "file:///adapters/a.safetensors", "sha256": "feed"},
        "base_model": "qwen3-4b",
        "quantization": "bf16",
        "serving_runtime": "vllm",
        "serves_as": "acme-support",
        "evalset_hash": evalset_hash,
        "corpus_manifest": "cafe0123",
    })
    .to_string();
    let adapter_grain =
        sub.add_fact_at("agent:harness", "model:acme-support", "mg:adapter", &tuple, 9_000);

    let e = Engine::with_builtins();
    e.run(&mut sub.inner, &RunOptions::default(), 10_000).unwrap();

    let rec = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| r.action_kind == ActionKind::AdapterRevision)
        .expect("the adapter revision");
    assert_eq!(rec.evalset_hash.as_deref(), Some(evalset_hash.as_str()));
    assert_eq!(rec.target_ref, "model:acme-support");
    assert!(rec.evidence.contains(&adapter_grain));
    // Auto-apply is structurally impossible: the run left it Pending even
    // though the engine ran with its default (and any) policy — the class is
    // excluded by name and the analyzer is AutoApplyClass::Never.
    assert_eq!(rec.status, RecStatus::Pending);
    let hash = rec.hash.clone();
    let scopes = ScopeSet::all();
    e.review(
        &mut sub.inner, &hash, Decision::Approve, "user:reviewer",
        ObserverType::Human, &scopes, "corpus + lineage reviewed", 11_000,
    )
    .unwrap();

    // 1. Ungated apply — refused.
    match e.apply(&mut sub.inner, &hash, "user:reviewer", ObserverType::Human, &scopes, "ship it", false, 12_000) {
        Err(Error::InvalidProposal(m)) => assert!(m.contains("gating run"), "{m}"),
        other => panic!("ungated adapter apply must refuse, got {other:?}"),
    }
    // 2. Wrong evalset — refused (Rule E1's pin).
    let wrong = GatingEvidence { evalset_hash: "not-the-pin".into(), run_id: "eval-1".into(), passed: 3, failed: 0 };
    match e.apply_gated(&mut sub.inner, &hash, "user:reviewer", ObserverType::Human, &scopes, "ship", false, &wrong, 12_100) {
        Err(Error::InvalidProposal(m)) => assert!(m.contains("pinned"), "{m}"),
        other => panic!("wrong-evalset apply must refuse, got {other:?}"),
    }
    // 3. A failing gate admits nothing.
    let failing = GatingEvidence { evalset_hash: evalset_hash.clone(), run_id: "eval-2".into(), passed: 2, failed: 1 };
    match e.apply_gated(&mut sub.inner, &hash, "user:reviewer", ObserverType::Human, &scopes, "ship", false, &failing, 12_200) {
        Err(Error::InvalidProposal(m)) => assert!(m.contains("failing gate"), "{m}"),
        other => panic!("failing-gate apply must refuse, got {other:?}"),
    }
    // 4. Clean gate, live pin: applies, writing the promotion Fact.
    let clean = GatingEvidence { evalset_hash: evalset_hash.clone(), run_id: "eval-3".into(), passed: 3, failed: 0 };
    e.apply_gated(&mut sub.inner, &hash, "user:reviewer", ObserverType::Human, &scopes, "gated and green", false, &clean, 12_300)
        .unwrap();
    let promotion = {
        use crate::substrate::SubstrateRead;
        sub.inner
            .grains_of_type("fact", Some("areev-loop"), Default::default())
            .unwrap()
            .into_iter()
            .find(|g| g.str_field("relation") == Some("mg:adapter_promotion") && g.is_live())
            .expect("the promotion grain")
    };
    assert_eq!(promotion.str_field("subject"), Some("model:acme-support"));
    assert_eq!(promotion.str_field("gating_evalset"), Some(evalset_hash.as_str()));
    assert_eq!(promotion.str_field("gating_run_id"), Some("eval-3"));

    // 5. One candidate per served model: while the promotion is live, the
    // analyzer proposes nothing new for this subject.
    e.run(&mut sub.inner, &RunOptions::default(), 13_000).unwrap();
    assert!(
        e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .iter()
            .all(|r| r.action_kind != ActionKind::AdapterRevision),
        "a promoted model must not re-propose"
    );

    // 6. Rollback retracts the promotion (the recorded inverse) …
    e.rollback(&mut sub.inner, &hash, "user:reviewer", ObserverType::Human, &scopes, "regressed in prod", 14_000)
        .unwrap();
    {
        use crate::substrate::SubstrateRead;
        let live = sub.inner
            .grains_of_type("fact", Some("areev-loop"), Default::default())
            .unwrap()
            .into_iter()
            .filter(|g| g.str_field("relation") == Some("mg:adapter_promotion") && g.is_live())
            .count();
        assert_eq!(live, 0, "rollback must retract the promotion");
    }
    // … and the still-live candidate is re-proposed — the situation
    // returned. Retiring the mg:adapter grain is how a host silences it.
    e.run(&mut sub.inner, &RunOptions::default(), 15_000).unwrap();
    assert!(
        e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .iter()
            .any(|r| r.action_kind == ActionKind::AdapterRevision),
        "post-rollback the candidate must be re-proposed"
    );
}

// ── Issue #29: evalset-backed outcome metric ──────────────────────────────
// `areev loop outcomes` could only close the receipt on internal recurrence
// counts. An evalset run is ALSO internal, bounded and attributable, so it can
// carry external correctness without breaking the honesty rule — provided the
// measurement never scores against a run that predates the apply.
mod evalset_outcome {
    use super::*;
    use crate::recommendation::MetricSnapshot;

    const EVALSET: &str = "abc123";

    fn snapshot(field: &str, baseline: f64, higher_is_better: bool) -> MetricSnapshot {
        MetricSnapshot {
            metric: format!("evalset:{EVALSET}:{field}"),
            baseline,
            unit: "ratio".into(),
            n: 184,
            window: "evalset".into(),
            subject: None,
            namespace: None,
            relation: None,
            query: String::new(),
            review_after_ms: 86_400_000,
            horizons_ms: vec![],
            checkpoints: Vec::new(),
            higher_is_better,
        }
    }

    /// Journal a summary the way `areev eval run` does.
    fn journal_run(sub: &mut TestSubstrate, run_id: &str, at_ms: i64, extra: serde_json::Value) {
        let mut summary = serde_json::json!({"run_id": run_id, "passed": 1, "failed": 0});
        if let (Some(o), Some(e)) = (summary.as_object_mut(), extra.as_object()) {
            for (k, v) in e {
                o.insert(k.clone(), v.clone());
            }
        }
        sub.add_fact_at(
            "agent:harness",
            &format!("evalset:{EVALSET}"),
            "mg:eval_run",
            &summary.to_string(),
            at_ms,
        );
    }

    fn measure(sub: &TestSubstrate, m: &MetricSnapshot, since: i64) -> Option<f64> {
        crate::engine::measure_metric(&sub.inner, m, since).unwrap()
    }

    #[test]
    fn resolves_a_host_field_from_the_newest_run() {
        let mut sub = TestSubstrate::new();
        journal_run(&mut sub, "eval-1", 1_000, serde_json::json!({"category_accuracy": 0.71}));
        journal_run(&mut sub, "eval-2", 2_000, serde_json::json!({"category_accuracy": 0.92}));
        let m = snapshot("category_accuracy", 0.71, true);
        assert_eq!(measure(&sub, &m, 500), Some(0.92), "the newest run is the current value");
    }

    #[test]
    fn a_run_that_predates_the_apply_is_not_evidence() {
        // The failure this prevents is a FABRICATED receipt: scoring the
        // baseline run against itself reports "held" forever, which reads as
        // proof the change worked.
        let mut sub = TestSubstrate::new();
        journal_run(&mut sub, "eval-1", 1_000, serde_json::json!({"category_accuracy": 0.71}));
        let m = snapshot("category_accuracy", 0.71, true);
        assert_eq!(
            measure(&sub, &m, 5_000),
            None,
            "no run since the apply means NOT YET MEASURABLE, not 'held'"
        );
        // Once a fresh run lands, it measures.
        journal_run(&mut sub, "eval-2", 6_000, serde_json::json!({"category_accuracy": 0.92}));
        assert_eq!(measure(&sub, &m, 5_000), Some(0.92));
    }

    #[test]
    fn promoted_fields_work_without_the_host_adding_any() {
        let mut sub = TestSubstrate::new();
        sub.add_fact_at(
            "agent:harness",
            &format!("evalset:{EVALSET}"),
            "mg:eval_run",
            &serde_json::json!({"run_id": "eval-1", "passed": 150, "failed": 34}).to_string(),
            1_000,
        );
        assert_eq!(measure(&sub, &snapshot("failed", 0.0, false), 0), Some(34.0));
        assert_eq!(measure(&sub, &snapshot("passed", 0.0, true), 0), Some(150.0));
        assert_eq!(measure(&sub, &snapshot("total", 0.0, false), 0), Some(184.0));
        let rate = measure(&sub, &snapshot("error_rate", 0.0, false), 0).unwrap();
        assert!((rate - 34.0 / 184.0).abs() < 1e-9, "error_rate = failed/total, got {rate}");
    }

    #[test]
    fn degenerate_and_malformed_inputs_measure_nothing_rather_than_guessing() {
        let mut sub = TestSubstrate::new();
        // An empty evalset must not divide by zero into NaN.
        sub.add_fact_at(
            "agent:harness",
            &format!("evalset:{EVALSET}"),
            "mg:eval_run",
            &serde_json::json!({"run_id": "eval-0", "passed": 0, "failed": 0}).to_string(),
            1_000,
        );
        assert_eq!(measure(&sub, &snapshot("error_rate", 0.0, false), 0), None);
        // A field the summary never recorded is unmeasurable, not zero.
        assert_eq!(measure(&sub, &snapshot("category_accuracy", 0.0, true), 0), None);
        // A malformed metric string resolves to nothing.
        let mut bad = snapshot("x", 0.0, false);
        bad.metric = "evalset:onlyhash".into();
        assert_eq!(measure(&sub, &bad, 0), None);
        // A different evalset's runs never leak in.
        let mut other = snapshot("failed", 0.0, false);
        other.metric = "evalset:deadbeef:failed".into();
        assert_eq!(measure(&sub, &other, 0), None);
    }

    #[test]
    fn a_summary_missing_its_counts_is_dropped_not_defaulted() {
        // Fail-closed: at the apply gate an absent `failed` must never read as
        // "zero failures".
        let mut sub = TestSubstrate::new();
        sub.add_fact_at(
            "agent:harness",
            &format!("evalset:{EVALSET}"),
            "mg:eval_run",
            &serde_json::json!({"run_id": "eval-x", "category_accuracy": 0.99}).to_string(),
            1_000,
        );
        assert_eq!(measure(&sub, &snapshot("category_accuracy", 0.5, true), 0), None);
        assert!(crate::eval::eval_runs(&sub.inner, EVALSET, None).unwrap().is_empty());
    }

    #[test]
    fn the_gating_and_outcome_edges_read_the_same_runs() {
        let mut sub = TestSubstrate::new();
        journal_run(&mut sub, "eval-1", 1_000, serde_json::json!({}));
        journal_run(&mut sub, "eval-2", 2_000, serde_json::json!({}));
        let by_id = crate::eval::eval_run_by_id(&sub.inner, EVALSET, "eval-1")
            .unwrap()
            .expect("gating edge finds the named run");
        assert_eq!(by_id.run_id, "eval-1");
        let newest = crate::eval::newest_eval_run(&sub.inner, EVALSET, None)
            .unwrap()
            .expect("outcome edge finds the newest run");
        assert_eq!(newest.run_id, "eval-2");
        assert!(crate::eval::eval_run_by_id(&sub.inner, EVALSET, "eval-nope").unwrap().is_none());
    }
}


// ---- checkpoints in the deployment's unit ----------------------------------

/// The MockLlm + policy scaffolding every checkpoint test shares: one lesson
/// proposed over one cited fact, an evalset the policy names, and a journal
/// helper. `checkpoints` is the policy's schedule.
fn lesson_under_evalset(checkpoints: &str) -> (TestSubstrate, Engine, String) {
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("capture", "correction", "vendor missing");
    let llm = MockLlm {
        discover: format!(
            r#"{{"recommendations":[{{"summary":"dates are being standardised","target":"entity:test/capture","evidence":["{h1}"],"confidence":0.9,"proposal":{{"kind":"lesson","lesson":"Copy the file date exactly as printed."}}}}]}}"#
        ),
        ground: r#"{"results":[{"id":0,"supported":true,"reason":"ok"}]}"#.into(),
        verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9,"reason":"ok"}]}"#.into(),
        enrich: r#"{"notes":[]}"#.into(),
    };
    let policy = Policy::from_json(&format!(
        r#"{{"outcome_evalset": {{"hash": "heldout1", "field": "exact", "higher_is_better": true, "checkpoints": {checkpoints}}}}}"#
    ))
    .unwrap();
    let e = Engine::with_builtins().with_llm(Box::new(llm)).with_policy(policy);
    (sub, e, h1)
}

fn journal_exact(sub: &mut TestSubstrate, run_id: &str, exact: u64, at: i64) {
    sub.add_fact_at(
        "agent:harness",
        "evalset:heldout1",
        "mg:eval_run",
        &format!(r#"{{"run_id":"{run_id}","passed":{exact},"failed":{},"exact":{exact}}}"#, 100 - exact),
        at,
    );
}

/// A benchmark journals one graded run per episode and finishes a family in
/// minutes; with `after_runs: 1` the verdict lands at the pass after the next
/// run, with the clock barely moved — the schedule that was measured to fire
/// zero verdicts across 78 governed runs under the day-long default.
#[test]
fn a_run_checkpoint_comes_due_at_the_next_graded_run_not_a_day_later() {
    use crate::model::Origin;
    use crate::recommendation::Checkpoint;
    let t = 5_000_000;
    let scopes = ScopeSet::all();
    let (mut sub, e, _) = lesson_under_evalset(r#"[{"after_runs": 1}]"#);
    journal_exact(&mut sub, "eval-0", 40, t - 1_000);
    e.run(&mut sub.inner, &RunOptions::default(), t).unwrap();
    let rec = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }))
        .expect("the lesson is proposed");
    let m = rec.metric.as_ref().expect("the policy attached a metric");
    assert_eq!(m.schedule(), vec![Checkpoint::AfterRuns(1)], "the snapshot carries the host's unit");
    assert!(m.horizons_ms.is_empty(), "no time schedule is invented beside it");
    e.review(&mut sub.inner, &rec.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "ok", t + 1).unwrap();
    e.apply(&mut sub.inner, &rec.hash, "user:a", ObserverType::Human, &scopes, "apply", false, t + 2).unwrap();

    // No run since the apply: not due, no matter how much time passes.
    e.run(&mut sub.inner, &RunOptions::default(), t + 3 * DAY).unwrap();
    assert!(e.outcomes(&sub.inner).unwrap().is_empty(), "a run checkpoint never fires on the clock alone");

    // One graded run after the apply, seconds later: due at the very next pass.
    journal_exact(&mut sub, "eval-1", 20, t + 3 * DAY + 10);
    e.run(&mut sub.inner, &RunOptions::default(), t + 3 * DAY + 20).unwrap();
    let v: Vec<_> = e.outcomes(&sub.inner).unwrap().into_iter().filter(|o| o.rec_hash == rec.hash).collect();
    assert_eq!(v.len(), 1, "measured exactly once");
    assert_eq!((v[0].baseline, v[0].current, v[0].verdict.as_str()), (40.0, 20.0, "regressed"));
    assert_eq!(v[0].checkpoint, Some(Checkpoint::AfterRuns(1)), "the record says which unit fired");
    assert_eq!(v[0].horizon_ms, 0, "and does not pretend to be a time checkpoint");
    assert!(
        e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .iter()
            .any(|r| r.analyzer.starts_with("loop.outcome_review")),
        "the regression proposes the revert — the half of governance the default horizon had switched off"
    );
    // Another run does not re-measure a checkpoint already taken.
    journal_exact(&mut sub, "eval-2", 10, t + 3 * DAY + 30);
    e.run(&mut sub.inner, &RunOptions::default(), t + 3 * DAY + 40).unwrap();
    assert_eq!(e.outcomes(&sub.inner).unwrap().iter().filter(|o| o.rec_hash == rec.hash).count(), 1);
}

/// A chat deployment counts activity: `after_grains` fires once enough has
/// been written since the apply, and the measurement still reads only runs
/// journaled after it.
#[test]
fn a_grain_checkpoint_counts_activity_since_the_apply() {
    use crate::model::Origin;
    use crate::recommendation::Checkpoint;
    let t = 5_000_000;
    let scopes = ScopeSet::all();
    let (mut sub, e, _) = lesson_under_evalset(r#"[{"after_grains": 3}]"#);
    journal_exact(&mut sub, "eval-0", 40, t - 1_000);
    e.run(&mut sub.inner, &RunOptions::default(), t).unwrap();
    let rec = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }))
        .unwrap();
    e.review(&mut sub.inner, &rec.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "ok", t + 1).unwrap();
    e.apply(&mut sub.inner, &rec.hash, "user:a", ObserverType::Human, &scopes, "apply", false, t + 2).unwrap();
    // Two grains since the apply: not yet.
    //
    // The journaled eval run is NOT one of them. It lives in `agent:harness`,
    // and the activity count is an all-namespace scan, which hides governance
    // namespaces. This test used to count it, because the reference substrate
    // was more permissive than any real one — the fake said two where
    // production said one. Counting what production counts is the point.
    journal_exact(&mut sub, "eval-1", 45, t + 10);
    sub.add_fact_at("test", "x", "y", "z", t + 11);
    sub.add_fact_at("test", "x", "y2", "z2", t + 12);
    e.run(&mut sub.inner, &RunOptions::default(), t + 13).unwrap();
    assert!(e.outcomes(&sub.inner).unwrap().is_empty());
    // A third: due. Current is the newest run after the apply (45 ≥ 40: held).
    sub.add_fact_at("test", "x", "y", "w", t + 14);
    e.run(&mut sub.inner, &RunOptions::default(), t + 15).unwrap();
    let v = e.outcomes(&sub.inner).unwrap();
    assert_eq!(v.len(), 1);
    assert_eq!((v[0].verdict.as_str(), v[0].checkpoint), ("held", Some(Checkpoint::AfterGrains(3))));
}

/// The pre-checkpoint spelling still means what it meant: a state blob with
/// `measured: [86400000]` and a policy with only `horizons_ms` read as time.
#[test]
fn checkpoint_serde_keeps_bare_integers_as_milliseconds() {
    use crate::recommendation::Checkpoint;
    let v: Vec<Checkpoint> = serde_json::from_str(r#"[86400000, {"after_runs": 2}, {"after_grains": 7}, {"after_ms": 5}]"#).unwrap();
    assert_eq!(
        v,
        vec![Checkpoint::AfterMs(86_400_000), Checkpoint::AfterRuns(2), Checkpoint::AfterGrains(7), Checkpoint::AfterMs(5)]
    );
    // An all-time schedule serializes exactly as the old Vec<i64> did.
    assert_eq!(serde_json::to_string(&vec![Checkpoint::AfterMs(1), Checkpoint::AfterMs(2)]).unwrap(), "[1,2]");
    assert_eq!(serde_json::to_string(&Checkpoint::AfterRuns(3)).unwrap(), r#"{"after_runs":3}"#);
    assert_eq!(Checkpoint::AfterMs(86_400_000).label(), "1d");
    assert_eq!(Checkpoint::AfterMs(7_200_000).label(), "2h");
    assert_eq!(Checkpoint::AfterRuns(1).label(), "1 run");
    assert_eq!(Checkpoint::AfterGrains(50).label(), "50 grains");
    for bad in [r#"-1"#, r#""1d""#, r#"{"after_turns":1}"#, r#"{"after_runs":1,"after_ms":1}"#, r#"{"after_runs":-1}"#] {
        assert!(serde_json::from_str::<Checkpoint>(bad).is_err(), "{bad}");
    }
    // A legacy state blob decodes into the typed map.
    let p = crate::config::LoopPersisted::from_value(serde_json::json!({"measured": {"h": [86400000]}})).unwrap();
    assert_eq!(p.measured["h"], vec![Checkpoint::AfterMs(86_400_000)]);
}

// ---- cadence ----------------------------------------------------------------

fn add_event(sub: &mut TestSubstrate, session: &str, at: i64) {
    let mut fields = serde_json::Map::new();
    fields.insert("content".into(), serde_json::json!("hello"));
    fields.insert("role".into(), serde_json::json!("user"));
    fields.insert("session_id".into(), serde_json::json!(session));
    fields.insert("namespace".into(), serde_json::json!("test"));
    sub.inner.insert(crate::model::GrainRecord {
        hash: String::new(),
        grain_type: "event".into(),
        namespace: "test".into(),
        created_at_ms: at,
        valid_to_ms: None,
        superseded_by: None,
        fields,
    });
}

#[test]
fn cadence_counts_turns_and_sessions_and_yields_to_flags_and_sweeps() {
    let t = 10_000;
    // every_events: 3 — two turns is not a tick, three is.
    let p = Policy::from_json(r#"{"cadence": {"every_events": 3}}"#).unwrap();
    let e = Engine::with_builtins().with_policy(p);
    let mut sub = TestSubstrate::new();
    add_event(&mut sub, "s1", t + 1);
    add_event(&mut sub, "s1", t + 2);
    let r = e.run(&mut sub.inner, &RunOptions::default(), t + 10).unwrap();
    assert_eq!((r.outcome, r.skip_reason), (RunOutcome::Skipped, Some(SkipReason::CadenceNotDue)));
    add_event(&mut sub, "s1", t + 3);
    let r = e.run(&mut sub.inner, &RunOptions::default(), t + 11).unwrap();
    assert_eq!(r.outcome, RunOutcome::Ran, "the third turn makes the pass due");
    // The watermark advanced: the same three turns do not fire it again.
    let r = e.run(&mut sub.inner, &RunOptions::default(), t + 12).unwrap();
    assert_eq!(r.skip_reason, Some(SkipReason::CadenceNotDue));

    // every_sessions: 1 — reflect once per conversation. Ten turns in one
    // session is one session.
    let p = Policy::from_json(r#"{"cadence": {"every_sessions": 2}}"#).unwrap();
    let e = Engine::with_builtins().with_policy(p);
    let mut sub = TestSubstrate::new();
    for i in 0..10 {
        add_event(&mut sub, "only", t + i);
    }
    assert_eq!(e.run(&mut sub.inner, &RunOptions::default(), t + 20).unwrap().skip_reason, Some(SkipReason::CadenceNotDue));
    add_event(&mut sub, "another", t + 15);
    assert_eq!(e.run(&mut sub.inner, &RunOptions::default(), t + 21).unwrap().outcome, RunOutcome::Ran);

    // every_ms: time since the last run; OR with every_grains — whichever first.
    let p = Policy::from_json(r#"{"cadence": {"every_ms": 3600000, "every_grains": 2}}"#).unwrap();
    let e = Engine::with_builtins().with_policy(p);
    let mut sub = TestSubstrate::new();
    sub.add_fact_at("test", "a", "b", "c", t);
    assert_eq!(e.run(&mut sub.inner, &RunOptions::default(), t + 1).unwrap().outcome, RunOutcome::Ran, "never ran → due");
    sub.add_fact_at("test", "a", "b", "d", t + 2);
    assert_eq!(e.run(&mut sub.inner, &RunOptions::default(), t + 3).unwrap().skip_reason, Some(SkipReason::CadenceNotDue));
    assert_eq!(e.run(&mut sub.inner, &RunOptions::default(), t + 3_600_005).unwrap().outcome, RunOutcome::Ran, "an hour later: time fires");

    // Flags override the block (host CLI flags > policy file): --min-new 1 on a
    // file the cadence would skip runs; and a sweep is a command, not a tick.
    let p = Policy::from_json(r#"{"cadence": {"every_grains": 100}}"#).unwrap();
    let e = Engine::with_builtins().with_policy(p);
    let mut sub = TestSubstrate::new();
    sub.add_fact("a", "b", "c");
    assert_eq!(e.run(&mut sub.inner, &RunOptions::default(), t).unwrap().skip_reason, Some(SkipReason::CadenceNotDue));
    let flags = RunOptions { min_new: Some(1), ..Default::default() };
    assert_eq!(e.run(&mut sub.inner, &flags, t + 1).unwrap().outcome, RunOutcome::Ran);
    let sweep = RunOptions { full_sweep: true, ..Default::default() };
    assert_eq!(e.run(&mut sub.inner, &sweep, t + 2).unwrap().outcome, RunOutcome::Ran);
    // And an unset cadence changes nothing: always due.
    let e = Engine::with_builtins();
    let mut sub = TestSubstrate::new();
    assert_eq!(e.run(&mut sub.inner, &RunOptions::default(), t).unwrap().outcome, RunOutcome::Ran);
}

// ---- the evidence floor -------------------------------------------------------

/// Under `min_evidence: 2` a lesson citing one grain is stored as a finding a
/// reviewer can read, but carries nothing they could apply; the funnel says
/// why. Under the default it is applicable, as before.
#[test]
fn a_thin_draft_stays_advisory_under_the_evidence_floor() {
    use crate::model::Origin;
    let t = 5_000_000;
    let mk = |min: u32| {
        let mut sub = TestSubstrate::new();
        let h1 = sub.add_fact("capture", "correction", "vendor missing");
        let llm = MockLlm {
            discover: format!(
                r#"{{"recommendations":[{{"summary":"a pattern","target":"entity:test/capture","evidence":["{h1}"],"confidence":0.9,"proposal":{{"kind":"lesson","lesson":"Record the vendor on every invoice."}}}}]}}"#
            ),
            ground: r#"{"results":[{"id":0,"supported":true,"reason":"ok"}]}"#.into(),
            verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9,"reason":"ok"}]}"#.into(),
            enrich: r#"{"notes":[]}"#.into(),
        };
        let policy = Policy::from_json(&format!(r#"{{"min_evidence": {min}}}"#)).unwrap();
        (sub, Engine::with_builtins().with_llm(Box::new(llm)).with_policy(policy))
    };
    let (mut sub, e) = mk(2);
    let r = e.run(&mut sub.inner, &RunOptions::default(), t).unwrap();
    assert_eq!(r.llm_funnel.as_ref().map(|f| f.advisory_thin_evidence), Some(1));
    let rec = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }))
        .expect("stored — a person may still want to see it");
    assert_eq!(rec.action_kind, crate::model::ActionKind::Flag, "but nothing to apply");
    let (mut sub, e) = mk(1);
    let r = e.run(&mut sub.inner, &RunOptions::default(), t).unwrap();
    assert_eq!(r.llm_funnel.as_ref().map(|f| f.advisory_thin_evidence), Some(0));
    let rec = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }))
        .unwrap();
    assert_eq!(rec.action_kind, crate::model::ActionKind::ClusterFailure, "the default: one instance may become a rule");
}


// ---- skill authoring ------------------------------------------------------------

/// The proposer sees a successful trajectory — tool calls with their inputs —
/// and authors a Skill: name from the target, ordered steps as instructions,
/// `when_to_use` as the routing cue. Applied, it is a live Skill grain in the
/// evidence's namespace; proposed again under the same name, it supersedes
/// rather than duplicating.
#[test]
fn the_proposer_authors_a_skill_from_a_successful_trajectory_and_patches_it_by_name() {
    use crate::model::Origin;
    use crate::substrate::{ReadOpts, SubstrateRead};
    let t = 5_000_000;
    let scopes = ScopeSet::all();
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_tool_call("helpdesk_list_tickets", false, "TK-1 open, TK-2 open");
    let h2 = sub.add_tool_call("helpdesk_update_ticket", false, "TK-2 updated: priority=high tags=[deploy-child]");
    let draft_citing = |cites: &str, steps: &str| {
        format!(
            r#"{{"recommendations":[{{"summary":"a repeatable triage","target":"entity:test/group-deploy-children","evidence":[{cites}],"confidence":0.9,"proposal":{{"kind":"skill","description":"Group child failures under their deploy event","when_to_use":"open tickets share a release_hash with a deploy-event ticket","steps":{steps}}}}}]}}"#
        )
    };
    let draft = |steps: &str| draft_citing(&format!(r#""{h1}","{h2}""#), steps);
    let mk = |discover: String| MockLlm {
        discover,
        ground: r#"{"results":[{"id":0,"supported":true,"reason":"ok"}]}"#.into(),
        verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9,"reason":"ok"}]}"#.into(),
        enrich: r#"{"notes":[]}"#.into(),
    };
    let e = Engine::with_builtins().with_llm(Box::new(mk(draft(
        r#"["List open tickets with helpdesk_list_tickets","For each child-failure sharing the deploy event's release_hash, set priority=high and tags=[deploy-child, <release_hash>]","Do not update the root deploy-event ticket"]"#,
    ))));
    let r = e.run(&mut sub.inner, &RunOptions::default(), t).unwrap();
    assert_eq!(r.llm_funnel.as_ref().map(|f| f.stored), Some(1), "the skill reached the queue");
    let rec = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }))
        .unwrap();
    let text = rec.summary.render();
    assert!(text.contains("record skill: \"group-deploy-children\" (3 steps)"), "{text}");
    assert!(rec.rollbackable);
    e.review(&mut sub.inner, &rec.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "reusable", t + 1).unwrap();
    e.apply(&mut sub.inner, &rec.hash, "user:a", ObserverType::Human, &scopes, "apply", false, t + 2).unwrap();
    let skills = sub
        .inner
        .grains_of_type(crate::model::grain_type::SKILL, None, ReadOpts { live_only: true, since_ms: None })
        .unwrap();
    assert_eq!(skills.len(), 1);
    let sk = &skills[0];
    assert_eq!(sk.skill_name(), Some("group-deploy-children"));
    assert_eq!(sk.namespace, "test", "the evidence's namespace, never the model's");
    let instr = sk.str_field("instructions").unwrap();
    assert!(instr.starts_with("1. List open tickets"), "{instr}");
    assert!(instr.contains("\n3. Do not update"), "ordered, numbered: {instr}");
    assert!(sk.str_field("when_to_use").unwrap().contains("release_hash"));
    let first_hash = sk.hash.clone();

    // The same name again, with a changed procedure: a SUPERSEDE of the live
    // skill, so the memory holds one skill of that name, not two.
    let e2 = Engine::with_builtins().with_llm(Box::new(mk(draft(
        r#"["List open tickets with helpdesk_list_tickets","Set priority=critical on a 503 child failure, else high"]"#,
    ))));
    e2.run(&mut sub.inner, &RunOptions { full_sweep: true, ..Default::default() }, t + DAY).unwrap();
    let rec2 = e2
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }) && r.hash != rec.hash)
        .expect("a second, different skill proposal");
    match &rec2.proposal {
        crate::recommendation::Proposal::Cal { cal } => {
            assert!(cal.starts_with(&format!("SUPERSEDE {first_hash} WITH skill ")), "patched by name: {cal}")
        }
        other => panic!("{other:?}"),
    }
    e2.review(&mut sub.inner, &rec2.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "changed", t + DAY + 1).unwrap();
    e2.apply(&mut sub.inner, &rec2.hash, "user:a", ObserverType::Human, &scopes, "apply", false, t + DAY + 2).unwrap();
    let live = sub
        .inner
        .grains_of_type(crate::model::grain_type::SKILL, None, ReadOpts { live_only: true, since_ms: None })
        .unwrap();
    assert_eq!(live.len(), 1, "one live skill of that name");
    assert!(live[0].str_field("instructions").unwrap().contains("critical"));

    // Too thin to be a procedure, or disabled by policy: advisory, not a change.
    let mut sub3 = TestSubstrate::new();
    let a = sub3.add_tool_call("x", false, "ok");
    let thin = Engine::with_builtins().with_llm(Box::new(mk(draft_citing(&format!(r#""{a}""#), r#"["Just one step"]"#))));
    let r = thin.run(&mut sub3.inner, &RunOptions::default(), t).unwrap();
    assert_eq!(r.llm_funnel.as_ref().map(|f| f.evidence), Some(1), "a lone successful call is evidence under skill authoring: {:?}", r.llm_funnel);
    let only = thin.recommendations(&sub3.inner, Some(RecStatus::Pending)).unwrap().into_iter().find(|r| matches!(r.origin, Origin::Llm { .. })).unwrap();
    assert_eq!(only.action_kind, crate::model::ActionKind::Flag, "one step is not a procedure: stored as a finding, applies as nothing");
    // Skills off: a lone success is not evidence (the pre-skill bundle), and
    // even a skill the model returns anyway, over a cited failure, applies
    // as nothing.
    let mut sub4 = TestSubstrate::new();
    let b = sub4.add_tool_call("x", true, "boom");
    let off = Engine::with_builtins()
        .with_llm(Box::new(mk(draft_citing(&format!(r#""{b}""#), r#"["a","b","c"]"#))))
        .with_policy(Policy::from_json(r#"{"skills": {"enabled": false}}"#).unwrap());
    off.run(&mut sub4.inner, &RunOptions::default(), t).unwrap();
    let only = off.recommendations(&sub4.inner, Some(RecStatus::Pending)).unwrap().into_iter().find(|r| matches!(r.origin, Origin::Llm { .. })).unwrap();
    assert_eq!(only.action_kind, crate::model::ActionKind::Flag, "not offered by policy: even a returned skill applies as nothing");
}

/// The skill paragraph is in the instructions only when the host allows it,
/// so the vocabulary the model sees is the vocabulary that can apply.
#[test]
fn the_skill_kind_is_offered_only_under_policy() {
    use std::sync::{Arc, Mutex};
    struct Capture(Arc<Mutex<Vec<String>>>);
    impl crate::llm::LlmBackend for Capture {
        fn model(&self) -> &str {
            "capture"
        }
        fn complete(&self, request: &str) -> crate::error::Result<String> {
            self.0.lock().unwrap().push(request.to_string());
            Ok(r#"{"recommendations":[]}"#.into())
        }
    }
    let run = |policy: &str| -> bool {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let mut sub = TestSubstrate::new();
        // A FAILURE, so the model is reached under either policy — with
        // skills off a lone success is not evidence at all, which the
        // tool-failure evidence test pins separately.
        sub.add_tool_call("x", true, "boom");
        let e = Engine::with_builtins()
            .with_llm(Box::new(Capture(seen.clone())))
            .with_policy(Policy::from_json(policy).unwrap());
        let r = e.run(&mut sub.inner, &RunOptions::default(), 5_000_000).unwrap();
        let reqs = seen.lock().unwrap();
        let discover = reqs
            .iter()
            .find(|r| r.contains("\"op\":\"discover\""))
            .unwrap_or_else(|| panic!("discover was called; outcome {:?} funnel {:?}", r.outcome, r.llm_funnel));
        // `<skill-name>` occurs in the skill paragraph and nowhere else.
        discover.contains("<skill-name>")
    };
    assert!(run("{}"), "default: offered");
    assert!(!run(r#"{"skills": {"enabled": false}}"#), "disabled: not offered");
}


// ---- plan authoring -----------------------------------------------------------

/// A procedure with a branch is authored as a PLAN: a Workflow the runtime
/// validated (steps bound to tools the evidence shows were called, an edge
/// with a condition in the frozen grammar) and a Skill of the same name that
/// carries the prose. One batch, one review. The same name again supersedes
/// both — the patch `PC02_sop_patch` is about.
#[test]
fn the_proposer_authors_a_plan_as_a_validated_workflow_beside_its_skill() {
    use crate::model::Origin;
    use crate::substrate::{ReadOpts, SubstrateRead};
    let t = 5_000_000;
    let scopes = ScopeSet::all();
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_tool_call("helpdesk_list_tickets", false, "TK-1 open, TK-2 open, TK-3 open");
    let h2 = sub.add_tool_call("helpdesk_update_ticket", false, "TK-2 tagged shared-incident");
    let draft = |nodes: &str, edges: &str| {
        format!(
            r#"{{"recommendations":[{{"summary":"a repeatable triage with a branch","target":"entity:test/shared-incident-triage","evidence":["{h1}","{h2}"],"confidence":0.9,"proposal":{{"kind":"plan","description":"Triage a batch for a shared incident","when_to_use":"several open tickets mention one component","nodes":{nodes},"edges":{edges}}}}}]}}"#
        )
    };
    let mk = |discover: String| MockLlm {
        discover,
        ground: r#"{"results":[{"id":0,"supported":true,"reason":"ok"}]}"#.into(),
        verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9,"reason":"ok"}]}"#.into(),
        enrich: r#"{"notes":[]}"#.into(),
    };
    let nodes = r#"[{"id":"list_open","tool":"helpdesk_list_tickets","step":"List every open ticket"},{"id":"tag_shared","tool":"helpdesk_update_ticket","step":"Tag each ticket sharing the component with shared-incident, priority high"},{"id":"leave","tool":"helpdesk_update_ticket","step":"Leave resolution to on-call: do not close"}]"#;
    let edges = r#"[{"src":"list_open","dst":"tag_shared","cond":"shared_component == true"},{"src":"tag_shared","dst":"leave"}]"#;
    let e = Engine::with_builtins().with_llm(Box::new(mk(draft(nodes, edges))));
    let r = e.run(&mut sub.inner, &RunOptions::default(), t).unwrap();
    assert_eq!(r.llm_funnel.as_ref().map(|f| f.stored), Some(1));
    let rec = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }))
        .unwrap();
    let text = rec.summary.render();
    assert!(text.contains("record plan: \"shared-incident-triage\" (3 steps, 2 edges)"), "{text}");
    match &rec.proposal {
        crate::recommendation::Proposal::Cal { cal } => {
            assert!(cal.starts_with("ADD skill "), "{cal}");
            assert!(cal.contains("\nADD workflow "), "one batch, two grains: {cal}");
        }
        other => panic!("{other:?}"),
    }
    e.review(&mut sub.inner, &rec.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "reusable", t + 1).unwrap();
    e.apply(&mut sub.inner, &rec.hash, "user:a", ObserverType::Human, &scopes, "apply", false, t + 2).unwrap();
    let live = |s: &TestSubstrate, gt: &str| s.inner.grains_of_type(gt, None, ReadOpts { live_only: true, since_ms: None }).unwrap();
    let skills = live(&sub, crate::model::grain_type::SKILL);
    let plans = live(&sub, crate::model::grain_type::WORKFLOW);
    assert_eq!((skills.len(), plans.len()), (1, 1));
    let sk = &skills[0];
    assert_eq!(sk.skill_name(), Some("shared-incident-triage"));
    let instr = sk.str_field("instructions").unwrap();
    assert!(instr.starts_with("1. list_open [helpdesk_list_tickets]: List every open ticket"), "{instr}");
    assert!(instr.contains("Flow:\n- list_open → tag_shared if shared_component == true\n- tag_shared → leave"), "{instr}");
    let wf = &plans[0];
    assert_eq!(wf.str_field("name"), Some("shared-incident-triage"));
    assert_eq!(wf.namespace, "test");
    assert_eq!(wf.fields["nodes"], serde_json::json!(["list_open", "tag_shared", "leave"]));
    assert_eq!(wf.fields["edges"][0]["cond"], serde_json::json!("shared_component == true"));
    let (skill_hash, plan_hash) = (sk.hash.clone(), wf.hash.clone());

    // Patched by name: a second plan of the same name supersedes both grains.
    let e2 = Engine::with_builtins().with_llm(Box::new(mk(draft(
        r#"[{"id":"list_open","tool":"helpdesk_list_tickets","step":"List open tickets"},{"id":"tag_shared","tool":"helpdesk_update_ticket","step":"Tag with shared-incident AND zone-correlated"}]"#,
        r#"[{"src":"list_open","dst":"tag_shared"}]"#,
    ))));
    e2.run(&mut sub.inner, &RunOptions { full_sweep: true, ..Default::default() }, t + DAY).unwrap();
    let rec2 = e2
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }) && r.hash != rec.hash)
        .unwrap();
    assert_eq!(rec2.action_kind, crate::model::ActionKind::Revise);
    match &rec2.proposal {
        crate::recommendation::Proposal::Cal { cal } => {
            assert!(cal.contains(&format!("SUPERSEDE {skill_hash} WITH skill ")), "{cal}");
            assert!(cal.contains(&format!("SUPERSEDE {plan_hash} WITH workflow ")), "{cal}");
        }
        other => panic!("{other:?}"),
    }
    e2.review(&mut sub.inner, &rec2.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "v2", t + DAY + 1).unwrap();
    e2.apply(&mut sub.inner, &rec2.hash, "user:a", ObserverType::Human, &scopes, "apply", false, t + DAY + 2).unwrap();
    assert_eq!((live(&sub, crate::model::grain_type::SKILL).len(), live(&sub, crate::model::grain_type::WORKFLOW).len()), (1, 1), "one live pair");
    assert!(live(&sub, crate::model::grain_type::SKILL)[0].str_field("instructions").unwrap().contains("zone-correlated"));

    // A graph the runtime would refuse is recorded as a SKILL, not discarded:
    // the procedure is the thing worth keeping, and a 30B proposer writes
    // conditions outside the frozen grammar often enough that dropping the
    // draft for it would throw the capture away (PERSIST.md §11 #27).
    let mut s6 = TestSubstrate::new();
    let a = s6.add_tool_call("helpdesk_list_tickets", false, "TK-1, TK-2");
    let b = s6.add_tool_call("helpdesk_update_ticket", false, "TK-1 tagged");
    let ungrammatical = format!(
        r#"{{"recommendations":[{{"summary":"s","target":"entity:test/triage","evidence":["{a}","{b}"],"confidence":0.9,"proposal":{{"kind":"plan","description":"Group and tag","when_to_use":"several open tickets share a component","nodes":[{{"id":"list_open","tool":"helpdesk_list_tickets","step":"List open tickets"}},{{"id":"tag","tool":"helpdesk_update_ticket","step":"Tag each"}}],"edges":[{{"src":"list_open","dst":"tag","cond":"tickets.length > 0"}},{{"src":"tag","dst":"end"}}]}}}}]}}"#
    );
    let e6 = Engine::with_builtins().with_llm(Box::new(mk(ungrammatical)));
    e6.run(&mut s6.inner, &RunOptions::default(), t).unwrap();
    let rec6 = e6
        .recommendations(&s6.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }))
        .expect("stored");
    assert_eq!(rec6.action_kind, crate::model::ActionKind::Record, "still applicable");
    let text6 = rec6.summary.render();
    assert!(text6.contains("record skill: \"triage\""), "recorded as a skill, not a plan: {text6}");
    match &rec6.proposal {
        crate::recommendation::Proposal::Cal { cal } => {
            assert!(cal.starts_with("ADD skill "), "{cal}");
            assert!(!cal.contains("ADD workflow"), "no unrunnable plan is minted: {cal}");
            assert!(cal.contains("tickets.length > 0"), "the model's own guard survives as prose: {cal}");
            assert!(cal.contains("tag → end"), "and so does the edge that named no step: {cal}");
        }
        other => panic!("{other:?}"),
    }
    e6.review(&mut s6.inner, &rec6.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "keep the procedure", t + 1).unwrap();
    e6.apply(&mut s6.inner, &rec6.hash, "user:a", ObserverType::Human, &scopes, "apply", false, t + 2).unwrap();
    assert_eq!(live(&s6, crate::model::grain_type::SKILL).len(), 1);
    assert_eq!(live(&s6, crate::model::grain_type::WORKFLOW).len(), 0, "and no workflow grain");

    // Not grounded, not runnable, or not allowed: advisory, never a change.
    let advisory = |sub: &mut TestSubstrate, e: &Engine| {
        e.run(&mut sub.inner, &RunOptions::default(), t).unwrap();
        e.recommendations(&sub.inner, Some(RecStatus::Pending))
            .unwrap()
            .into_iter()
            .find(|r| matches!(r.origin, Origin::Llm { .. }))
            .map(|r| r.action_kind)
    };
    // A step whose tool the evidence never shows keeps its instruction and
    // loses the attribution — a real procedure has steps that call nothing,
    // and a model writes those with a placeholder tool.
    let mut s3 = TestSubstrate::new();
    let a = s3.add_tool_call("helpdesk_list_tickets", false, "ok");
    let mixed = format!(
        r#"{{"recommendations":[{{"summary":"s","target":"entity:test/p","evidence":["{a}"],"confidence":0.9,"proposal":{{"kind":"plan","description":"d","when_to_use":"w","nodes":[{{"id":"x","tool":"helpdesk_list_tickets","step":"List the open tickets"}},{{"id":"y","tool":"tool","step":"Group them by component"}}],"edges":[{{"src":"x","dst":"y"}}]}}}}]}}"#
    );
    let e3 = Engine::with_builtins().with_llm(Box::new(mk(mixed)));
    e3.run(&mut s3.inner, &RunOptions::default(), t).unwrap();
    let r3 = e3.recommendations(&s3.inner, Some(RecStatus::Pending)).unwrap().into_iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. })).expect("stored");
    assert_eq!(r3.action_kind, crate::model::ActionKind::Record);
    match &r3.proposal {
        crate::recommendation::Proposal::Cal { cal } => {
            assert!(cal.contains("1. x [helpdesk_list_tickets]: List the open tickets"), "{cal}");
            assert!(cal.contains("2. y: Group them by component"), "unattributed, not dropped: {cal}");
            assert!(!cal.contains("[tool]"), "and never credited to a tool that does not exist: {cal}");
        }
        other => panic!("{other:?}"),
    }
    // No step calls anything the evidence shows: not a procedure the agent
    // carried out, and nothing a reviewer should be offered.
    let mut s3b = TestSubstrate::new();
    let a = s3b.add_tool_call("helpdesk_list_tickets", false, "ok");
    let ungrounded = format!(
        r#"{{"recommendations":[{{"summary":"s","target":"entity:test/p","evidence":["{a}"],"confidence":0.9,"proposal":{{"kind":"plan","description":"d","when_to_use":"w","nodes":[{{"id":"x","tool":"delete_everything","step":"s"}},{{"id":"y","tool":"nope","step":"s"}}],"edges":[]}}}}]}}"#
    );
    assert_eq!(advisory(&mut s3b, &Engine::with_builtins().with_llm(Box::new(mk(ungrounded)))), Some(crate::model::ActionKind::Flag));
    // An edge to a step that does not exist no longer costs the draft: the
    // graph is refused, the procedure is kept as a skill (asserted above).
    // What stays advisory is a step naming a tool the evidence never shows —
    // a fabrication, and nothing a reviewer should be offered.
    // plans off by policy
    let mut s5 = TestSubstrate::new();
    let a = s5.add_tool_call("helpdesk_list_tickets", true, "boom");
    let fine = format!(
        r#"{{"recommendations":[{{"summary":"s","target":"entity:test/p","evidence":["{a}"],"confidence":0.9,"proposal":{{"kind":"plan","description":"d","when_to_use":"w","nodes":[{{"id":"x","tool":"helpdesk_list_tickets","step":"s"}},{{"id":"y","tool":"helpdesk_list_tickets","step":"s"}}],"edges":[{{"src":"x","dst":"y"}}]}}}}]}}"#
    );
    let off = Engine::with_builtins()
        .with_llm(Box::new(mk(fine)))
        .with_policy(Policy::from_json(r#"{"plans": {"enabled": false}}"#).unwrap());
    assert_eq!(advisory(&mut s5, &off), Some(crate::model::ActionKind::Flag));
}

// ---- the Verify gate's second question: premise drift ---------------------------

fn applied_lesson_over(sub: &mut TestSubstrate, e: &Engine, t: i64) -> Recommendation {
    use crate::model::Origin;
    let scopes = ScopeSet::all();
    e.run(&mut sub.inner, &RunOptions::default(), t).unwrap();
    let rec = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| matches!(r.origin, Origin::Llm { .. }))
        .expect("the lesson is proposed");
    e.review(&mut sub.inner, &rec.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "ok", t + 1).unwrap();
    e.apply(&mut sub.inner, &rec.hash, "user:a", ObserverType::Human, &scopes, "apply", false, t + 2).unwrap();
    rec
}

fn lesson_llm(h1: &str) -> MockLlm {
    MockLlm {
        discover: format!(
            r#"{{"recommendations":[{{"summary":"the readiness rule is flagged stale","target":"entity:test/release","evidence":["{h1}"],"confidence":0.9,"proposal":{{"kind":"lesson","lesson":"Skip the Release readiness review when it is flagged as a stale target."}}}}]}}"#
        ),
        ground: r#"{"results":[{"id":0,"supported":true,"reason":"ok"}]}"#.into(),
        verify: r#"{"results":[{"id":0,"keep":true,"confidence":0.9,"reason":"ok"}]}"#.into(),
        enrich: r#"{"notes":[]}"#.into(),
    }
}

/// A lesson learned from a rule that is later REPLACED has lost its premise:
/// the gate records `drifted` and proposes the revert; applying it rolls the
/// lesson back. A value-identical supersession (consolidation) is not drift,
/// and the check is a policy switch.
#[test]
fn a_lesson_whose_cited_evidence_was_superseded_by_a_different_value_is_reverted() {
    use crate::substrate::OmsSubstrate;
    let t = 5_000_000;
    let scopes = ScopeSet::all();
    let mut sub = TestSubstrate::new();
    let h1 = sub.add_fact("release", "readiness_rule", "flagged: stale target for migration");
    let e = Engine::with_builtins().with_llm(Box::new(lesson_llm(&h1)));
    let rec = applied_lesson_over(&mut sub, &e, t);
    // Nothing moved yet: no drift, no revert.
    e.run(&mut sub.inner, &RunOptions::default(), t + 10).unwrap();
    assert!(e.outcomes(&sub.inner).unwrap().is_empty());

    // The rule the lesson was learned from is replaced by a DIFFERENT one.
    sub.inner
        .execute_cal(&format!(
            r#"SUPERSEDE {h1} WITH fact {{"subject":"release","relation":"readiness_rule","object":"REL-GAMMA: review before every deploy","namespace":"test"}}"#
        ))
        .unwrap();
    e.run(&mut sub.inner, &RunOptions::default(), t + 20).unwrap();
    let v: Vec<_> = e.outcomes(&sub.inner).unwrap().into_iter().filter(|o| o.rec_hash == rec.hash).collect();
    assert_eq!(v.len(), 1);
    assert_eq!((v[0].metric.as_str(), v[0].verdict.as_str(), v[0].current), ("premise_drift", "drifted", 1.0));
    let revert = e
        .recommendations(&sub.inner, Some(RecStatus::Pending))
        .unwrap()
        .into_iter()
        .find(|r| r.analyzer.starts_with("loop.outcome_review"))
        .expect("a revert is proposed");
    assert!(revert.summary.render().contains("premise moved"), "{}", revert.summary.render());
    // A further pass does not re-record the same drift.
    e.run(&mut sub.inner, &RunOptions::default(), t + 30).unwrap();
    assert_eq!(e.outcomes(&sub.inner).unwrap().iter().filter(|o| o.rec_hash == rec.hash).count(), 1);
    // Applying the revert rolls the lesson back.
    e.review(&mut sub.inner, &revert.hash, Decision::Approve, "user:a", ObserverType::Human, &scopes, "its premise changed", t + 31).unwrap();
    e.apply(&mut sub.inner, &revert.hash, "user:a", ObserverType::Human, &scopes, "revert", false, t + 32).unwrap();
    let statuses: std::collections::BTreeMap<_, _> = e
        .recommendations(&sub.inner, None)
        .unwrap()
        .into_iter()
        .map(|r| (r.hash, r.status))
        .collect();
    assert_eq!(statuses[&rec.hash], RecStatus::RolledBack);

    // Value-identical supersession is not drift.
    let mut sub2 = TestSubstrate::new();
    let h = sub2.add_fact("release", "readiness_rule", "flagged: stale target for migration");
    let e2 = Engine::with_builtins().with_llm(Box::new(lesson_llm(&h)));
    let rec2 = applied_lesson_over(&mut sub2, &e2, t);
    sub2.inner
        .execute_cal(&format!(
            r#"SUPERSEDE {h} WITH fact {{"subject":"release","relation":"readiness_rule","object":"Flagged: stale target for migration ","namespace":"test","confidence":0.99}}"#
        ))
        .unwrap();
    e2.run(&mut sub2.inner, &RunOptions::default(), t + 20).unwrap();
    assert!(e2.outcomes(&sub2.inner).unwrap().iter().all(|o| o.rec_hash != rec2.hash), "same value, different confidence: the premise stands");

    // A retracted premise IS drift.
    let mut sub3 = TestSubstrate::new();
    let h = sub3.add_fact("release", "readiness_rule", "flagged: stale target for migration");
    let e3 = Engine::with_builtins().with_llm(Box::new(lesson_llm(&h)));
    let rec3 = applied_lesson_over(&mut sub3, &e3, t);
    sub3.inner.execute_cal(&format!("FORGET {h}")).unwrap();
    e3.run(&mut sub3.inner, &RunOptions::default(), t + 20).unwrap();
    assert!(e3.outcomes(&sub3.inner).unwrap().iter().any(|o| o.rec_hash == rec3.hash && o.verdict == "drifted"));

    // Switched off by policy: nothing.
    let mut sub4 = TestSubstrate::new();
    let h = sub4.add_fact("release", "readiness_rule", "flagged: stale target for migration");
    let e4 = Engine::with_builtins()
        .with_llm(Box::new(lesson_llm(&h)))
        .with_policy(Policy::from_json(r#"{"premise_drift": false}"#).unwrap());
    let rec4 = applied_lesson_over(&mut sub4, &e4, t);
    sub4.inner
        .execute_cal(&format!(r#"SUPERSEDE {h} WITH fact {{"subject":"release","relation":"readiness_rule","object":"something else","namespace":"test"}}"#))
        .unwrap();
    e4.run(&mut sub4.inner, &RunOptions::default(), t + 20).unwrap();
    assert!(e4.outcomes(&sub4.inner).unwrap().iter().all(|o| o.rec_hash != rec4.hash));
}