eidetic-engine 0.15.1

Durable, local-first, explainable memory for coding agents.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
//! Command effect manifest (EE-TST-009).
//!
//! Defines a first-class taxonomy of what each public command may do,
//! enabling agents to mechanically choose safe commands and proving
//! that read-only commands stay read-only.
//!
//! Effect classes:
//! - `ReadOnly` — no durable mutation, safe to call mid-task
//! - `DerivedArtifactWrite` — writes rebuildable indexes/caches
//! - `DurableMemoryWrite` — writes memories, audit records
//! - `WorkspaceFileWrite` — writes workspace files beyond DB
//! - `ConfigWrite` — modifies configuration
//! - `ExternalIo` — network or subprocess I/O
//!
//! The manifest maps each command path to its default effect, dry-run
//! effect, allowed write surfaces, and idempotency posture.

use std::collections::HashMap;

/// Side-effect class names shared with the command-boundary matrix.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum SideEffectClass {
    /// No DB, index, cache, or filesystem mutation.
    ReadOnly,
    /// Current command is read-only or degraded; future writes need a new audited class.
    ReadOnlyNow,
    /// Report computed from explicit inputs without durable mutation.
    ReportOnly,
    /// Static reads are allowed; missing or judgment-heavy work degrades or hands off.
    ReadOnlyOrUnavailable,
    /// Append new records, or return an existing record by idempotency key.
    AppendOnly,
    /// Durable mutation in one audited transaction.
    AuditedMutation,
    /// Rebuild only derived, rebuildable assets keyed by source generation.
    DerivedAssetRebuild,
    /// Create or verify a side-path artifact without overwriting source data.
    SidePathArtifact,
    /// Long-running job mutation through a supervised job ledger.
    SupervisedJobs,
    /// Family contains both read-only and mutating subcommands.
    Mixed,
    /// No mutation until the real implementation exists.
    DegradedUnavailable,
    /// Read-only extraction today; future candidate writes require an explicit append path.
    ReportOnlyOrAppend,
    /// Read-only reports today; relation writes require an explicit audited transaction.
    ReportOnlyOrAuditedMutation,
}

impl SideEffectClass {
    /// Stable vocabulary token used in docs, JSON logs, and tests.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ReadOnly => "class=read_only",
            Self::ReadOnlyNow => "class=read_only_now",
            Self::ReportOnly => "class=report_only",
            Self::ReadOnlyOrUnavailable => "class=read_only_or_unavailable",
            Self::AppendOnly => "class=append_only",
            Self::AuditedMutation => "class=audited_mutation",
            Self::DerivedAssetRebuild => "class=derived_asset_rebuild",
            Self::SidePathArtifact => "class=side_path_artifact",
            Self::SupervisedJobs => "class=supervised_jobs",
            Self::Mixed => "class=mixed",
            Self::DegradedUnavailable => "class=degraded_unavailable",
            Self::ReportOnlyOrAppend => "class=report_only_or_append",
            Self::ReportOnlyOrAuditedMutation => "class=report_only_or_audited_mutation",
        }
    }

    /// `true` if this class forbids durable mutation.
    #[must_use]
    pub const fn declares_no_durable_mutation(self) -> bool {
        matches!(
            self,
            Self::ReadOnly
                | Self::ReadOnlyNow
                | Self::ReportOnly
                | Self::ReadOnlyOrUnavailable
                | Self::DegradedUnavailable
        )
    }

    /// `true` if this class must carry no-overwrite side-path behavior.
    #[must_use]
    pub const fn requires_no_overwrite_contract(self) -> bool {
        matches!(self, Self::SidePathArtifact)
    }

    /// `true` if this class must carry transaction/audit metadata.
    #[must_use]
    pub const fn requires_audited_transaction_contract(self) -> bool {
        matches!(self, Self::AppendOnly | Self::AuditedMutation)
    }
}

/// Effect class describing what a command may mutate.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum EffectClass {
    /// No durable mutation. Safe to call at any time.
    ReadOnly,
    /// Writes derived artifacts (indexes, caches) that can be rebuilt.
    DerivedArtifactWrite,
    /// Writes durable memory records, audit log, or user-visible state.
    DurableMemoryWrite,
    /// Writes files in the workspace beyond the database.
    WorkspaceFileWrite,
    /// Modifies configuration (ee.toml, workspace config).
    ConfigWrite,
    /// Performs external I/O (network, subprocess).
    ExternalIo,
}

impl EffectClass {
    /// Stable string for JSON serialization and logs.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ReadOnly => "read_only",
            Self::DerivedArtifactWrite => "derived_artifact_write",
            Self::DurableMemoryWrite => "durable_memory_write",
            Self::WorkspaceFileWrite => "workspace_file_write",
            Self::ConfigWrite => "config_write",
            Self::ExternalIo => "external_io",
        }
    }

    /// `true` if this effect class mutates durable user-visible state.
    #[must_use]
    pub const fn is_mutating(self) -> bool {
        !matches!(self, Self::ReadOnly)
    }

    /// `true` if mutations are rebuildable (indexes, caches).
    #[must_use]
    pub const fn is_derived(self) -> bool {
        matches!(self, Self::DerivedArtifactWrite)
    }
}

/// Cross-cutting mutation contract for a command manifest entry.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CommandMutationContract {
    /// Side-effect class from the command-boundary matrix vocabulary.
    pub side_effect_class: SideEffectClass,
    /// Named transaction scope, if the command mutates durable state.
    pub transaction_scope: Option<&'static str>,
    /// Idempotency key or retry posture.
    pub idempotency_key: Option<&'static str>,
    /// Audit surface written by the command, if any.
    pub audit_surface: Option<&'static str>,
    /// Effect on source database generation.
    pub db_generation_effect: &'static str,
    /// Effect on derived index or cache generation.
    pub index_generation_effect: &'static str,
    /// Dry-run or preview behavior, if exposed by this class.
    pub dry_run_behavior: Option<&'static str>,
    /// Recovery, rollback, or degraded behavior.
    pub recovery_behavior: &'static str,
    /// Side-path no-overwrite/no-delete behavior, when applicable.
    pub no_overwrite_behavior: Option<&'static str>,
    /// Degraded/error code returned when the command intentionally abstains.
    pub degraded_code: Option<&'static str>,
}

impl CommandMutationContract {
    #[must_use]
    pub const fn read_only() -> Self {
        Self {
            side_effect_class: SideEffectClass::ReadOnly,
            transaction_scope: None,
            idempotency_key: Some("full command argv and explicit inputs"),
            audit_surface: None,
            db_generation_effect: "none",
            index_generation_effect: "none",
            dry_run_behavior: None,
            recovery_behavior: "no durable changes to recover",
            no_overwrite_behavior: None,
            degraded_code: None,
        }
    }

    #[must_use]
    pub const fn derived_asset_rebuild(
        idempotency_key: &'static str,
        recovery_behavior: &'static str,
    ) -> Self {
        Self {
            side_effect_class: SideEffectClass::DerivedAssetRebuild,
            transaction_scope: Some("derived asset rebuild keyed by source generation"),
            idempotency_key: Some(idempotency_key),
            audit_surface: None,
            db_generation_effect: "source DB generation unchanged",
            index_generation_effect: "derived generation may advance to source generation",
            dry_run_behavior: Some("preview only; no derived files are written"),
            recovery_behavior,
            no_overwrite_behavior: None,
            degraded_code: None,
        }
    }

    #[must_use]
    pub const fn audited_mutation(idempotency_key: &'static str) -> Self {
        Self {
            side_effect_class: SideEffectClass::AuditedMutation,
            transaction_scope: Some("single DB transaction across write surfaces"),
            idempotency_key: Some(idempotency_key),
            audit_surface: Some("audit_log"),
            db_generation_effect: "advances on commit; unchanged on rollback",
            index_generation_effect: "queues or refreshes derived index after commit when applicable",
            dry_run_behavior: Some("no DB rows, audit rows, or derived index jobs are written"),
            recovery_behavior: "transaction rollback leaves no partial durable records",
            no_overwrite_behavior: None,
            degraded_code: None,
        }
    }

    #[must_use]
    pub const fn append_only(idempotency_key: &'static str) -> Self {
        Self {
            side_effect_class: SideEffectClass::AppendOnly,
            transaction_scope: Some("single append transaction across write surfaces"),
            idempotency_key: Some(idempotency_key),
            audit_surface: Some("audit_log"),
            db_generation_effect: "advances only when a new record commits; unchanged when idempotency key matches",
            index_generation_effect: "queues or refreshes derived index after new records commit",
            dry_run_behavior: Some("no DB rows, audit rows, or derived index jobs are written"),
            recovery_behavior: "transaction rollback leaves no partial append records",
            no_overwrite_behavior: None,
            degraded_code: None,
        }
    }

    #[must_use]
    pub const fn side_path_artifact(
        idempotency_key: &'static str,
        no_overwrite_behavior: &'static str,
    ) -> Self {
        Self {
            side_effect_class: SideEffectClass::SidePathArtifact,
            transaction_scope: Some("side-path artifact creation outside source DB mutation"),
            idempotency_key: Some(idempotency_key),
            audit_surface: Some("artifact manifest or audit_log when DB backing exists"),
            db_generation_effect: "source DB generation unchanged unless manifest audit is committed",
            index_generation_effect: "none",
            dry_run_behavior: Some("preview artifact path and manifest only; no files are written"),
            recovery_behavior: "partial side-path output is reported as failed, never deleted by ee, and not treated as a valid artifact",
            no_overwrite_behavior: Some(no_overwrite_behavior),
            degraded_code: None,
        }
    }

    #[must_use]
    pub const fn degraded_unavailable(degraded_code: &'static str) -> Self {
        Self {
            side_effect_class: SideEffectClass::DegradedUnavailable,
            transaction_scope: None,
            idempotency_key: Some("full command argv and explicit inputs"),
            audit_surface: None,
            db_generation_effect: "none",
            index_generation_effect: "none",
            dry_run_behavior: None,
            recovery_behavior: "returns an explicit degraded response without mutation",
            no_overwrite_behavior: None,
            degraded_code: Some(degraded_code),
        }
    }

    #[must_use]
    pub const fn supervised_jobs(
        idempotency_key: &'static str,
        recovery_behavior: &'static str,
    ) -> Self {
        Self {
            side_effect_class: SideEffectClass::SupervisedJobs,
            transaction_scope: Some("supervised steward job ledger"),
            idempotency_key: Some(idempotency_key),
            audit_surface: Some("audit_log"),
            db_generation_effect: "advances only when the configured job applies durable changes",
            index_generation_effect: "unchanged unless the steward job explicitly processes index work",
            dry_run_behavior: Some(
                "runs handler planning and reports candidate changes without committing job mutations",
            ),
            recovery_behavior,
            no_overwrite_behavior: None,
            degraded_code: None,
        }
    }

    #[must_use]
    pub fn declares_no_source_mutation(&self) -> bool {
        matches!(
            self.db_generation_effect,
            "none" | "source DB generation unchanged"
        )
    }
}

/// Idempotency behavior of a command.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum IdempotencyClass {
    /// Running twice produces the same observable outcome.
    Idempotent,
    /// Running twice may produce different outcomes (e.g., new memory IDs).
    NonIdempotent,
    /// Command supports `--dry-run` to preview without mutation.
    DryRunAvailable,
}

impl IdempotencyClass {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Idempotent => "idempotent",
            Self::NonIdempotent => "non_idempotent",
            Self::DryRunAvailable => "dry_run_available",
        }
    }
}

/// Runtime class for cancellation and budget behavior.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum RuntimeClass {
    /// Completes without meaningful async checkpoints.
    Immediate,
    /// Bounded local probes or DB reads; cancellation checked around boundaries.
    Bounded,
    /// Potentially long-running work with explicit budget/deadline checkpoints.
    LongRunning,
    /// Multi-stage work with commit/publish boundaries and cleanup policy.
    MultiStage,
    /// Work coordinated through a supervised child/job ledger.
    Supervised,
}

impl RuntimeClass {
    /// Stable vocabulary token used in boundary logs and tests.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Immediate => "immediate",
            Self::Bounded => "bounded",
            Self::LongRunning => "long_running",
            Self::MultiStage => "multi_stage",
            Self::Supervised => "supervised",
        }
    }

    /// `true` when commands in this class need an explicit runtime budget.
    #[must_use]
    pub const fn requires_budget(self) -> bool {
        matches!(
            self,
            Self::LongRunning | Self::MultiStage | Self::Supervised
        )
    }
}

/// Cross-cutting runtime contract for a command manifest entry.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CommandRuntimeContract {
    /// Classifies the runtime shape of the command.
    pub runtime_class: RuntimeClass,
    /// Default runtime budget in milliseconds, if the command is budgeted.
    pub default_budget_ms: Option<u64>,
    /// Stable cancellation checkpoints named in boundary logs.
    pub cancellation_points: &'static [&'static str],
    /// Policy for cleanup or audit after partial progress.
    pub partial_progress_policy: &'static str,
    /// Deterministic mapping from runtime outcome to CLI result/log outcome.
    pub outcome_mapping: &'static str,
}

impl CommandRuntimeContract {
    #[must_use]
    pub const fn immediate() -> Self {
        Self {
            runtime_class: RuntimeClass::Immediate,
            default_budget_ms: None,
            cancellation_points: &["before_start"],
            partial_progress_policy: "no durable partial progress is possible",
            outcome_mapping: "success or explicit degraded/error response",
        }
    }

    #[must_use]
    pub const fn bounded_read() -> Self {
        Self {
            runtime_class: RuntimeClass::Bounded,
            default_budget_ms: Some(30_000),
            cancellation_points: &["before_start", "between_bounded_probes"],
            partial_progress_policy: "read-only; no durable partial progress is possible",
            outcome_mapping: "success, degraded, or read-side error with no mutation",
        }
    }

    #[must_use]
    pub const fn long_running_derived() -> Self {
        Self {
            runtime_class: RuntimeClass::LongRunning,
            default_budget_ms: Some(300_000),
            cancellation_points: &["before_start", "source_scan", "before_publish"],
            partial_progress_policy: "derived artifacts publish atomically; failed generations are ignored until a complete publish",
            outcome_mapping: "success, cancelled, budget_exhausted, or index_error",
        }
    }

    #[must_use]
    pub const fn transactional() -> Self {
        Self {
            runtime_class: RuntimeClass::MultiStage,
            default_budget_ms: Some(60_000),
            cancellation_points: &["before_start", "before_transaction", "before_commit"],
            partial_progress_policy: "single transaction rollback leaves no unaudited durable records",
            outcome_mapping: "success, cancelled, budget_exhausted, storage_error, or degraded",
        }
    }

    #[must_use]
    pub const fn side_path_artifact() -> Self {
        Self {
            runtime_class: RuntimeClass::MultiStage,
            default_budget_ms: Some(120_000),
            cancellation_points: &["before_start", "before_artifact_write", "before_manifest"],
            partial_progress_policy: "partial side-path output is reported, never deleted by ee, and is not a valid artifact until manifested",
            outcome_mapping: "success, cancelled, budget_exhausted, storage_error, or degraded",
        }
    }

    #[must_use]
    pub const fn supervised_unavailable() -> Self {
        Self {
            runtime_class: RuntimeClass::Supervised,
            default_budget_ms: Some(300_000),
            cancellation_points: &["before_start", "before_child_spawn", "child_outcome"],
            partial_progress_policy: "supervised jobs must record child failure or cancellation before reporting completion",
            outcome_mapping: "degraded, cancelled, budget_exhausted, or supervised_child_failed",
        }
    }

    #[must_use]
    pub const fn supervised_jobs() -> Self {
        Self {
            runtime_class: RuntimeClass::Supervised,
            default_budget_ms: Some(300_000),
            cancellation_points: &[
                "before_start",
                "before_job_schedule",
                "before_handler",
                "handler_outcome",
            ],
            partial_progress_policy: "supervised jobs report skipped, failed, cancelled, or applied handler work in the runner result",
            outcome_mapping: "success, skipped, failed, cancelled, budget_exhausted, or supervised_child_failed",
        }
    }

    #[must_use]
    pub const fn requires_budget(&self) -> bool {
        self.runtime_class.requires_budget()
    }

    pub fn effective_budget_ms(
        &self,
        requested_budget_ms: Option<u64>,
    ) -> Result<Option<u64>, &'static str> {
        match requested_budget_ms {
            Some(0) => Err("runtime budget must be greater than zero"),
            Some(budget) => Ok(Some(budget)),
            None => Ok(self.default_budget_ms),
        }
    }
}

/// Allowed write surfaces for a command.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct WriteSurfaces {
    /// Database tables the command may write.
    pub db_tables: Vec<&'static str>,
    /// Derived artifact paths (relative to workspace).
    pub derived_paths: Vec<&'static str>,
    /// Workspace file patterns the command may write.
    pub workspace_files: Vec<&'static str>,
}

impl WriteSurfaces {
    #[must_use]
    pub const fn none() -> Self {
        Self {
            db_tables: Vec::new(),
            derived_paths: Vec::new(),
            workspace_files: Vec::new(),
        }
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.db_tables.is_empty()
            && self.derived_paths.is_empty()
            && self.workspace_files.is_empty()
    }
}

/// Effect manifest entry for a single command.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CommandEffect {
    /// Command path (e.g., "status", "memory list", "index rebuild").
    pub command_path: &'static str,
    /// Default effect class when run normally.
    pub default_effect: EffectClass,
    /// Effect class when run with `--dry-run` (if supported).
    pub dry_run_effect: Option<EffectClass>,
    /// Idempotency behavior.
    pub idempotency: IdempotencyClass,
    /// Surfaces the command may write.
    pub write_surfaces: WriteSurfaces,
    /// Cross-cutting side-effect and mutation-safety contract.
    pub mutation_contract: CommandMutationContract,
    /// Cross-cutting runtime, cancellation, and budget contract.
    pub runtime_contract: CommandRuntimeContract,
    /// Whether the command should run through a read-side snapshot lease.
    pub requires_read_snapshot: bool,
    /// Whether command requires audit log write.
    pub requires_audit: bool,
    /// Human-readable description of the effect.
    pub description: &'static str,
}

impl CommandEffect {
    /// Create a read-only effect entry.
    #[must_use]
    pub const fn read_only(command_path: &'static str, description: &'static str) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::ReadOnly,
            dry_run_effect: None,
            idempotency: IdempotencyClass::Idempotent,
            write_surfaces: WriteSurfaces::none(),
            mutation_contract: CommandMutationContract::read_only(),
            runtime_contract: CommandRuntimeContract::bounded_read(),
            requires_read_snapshot: false,
            requires_audit: false,
            description,
        }
    }

    /// Create a DB-backed read-only effect entry that must use a read snapshot.
    #[must_use]
    pub fn read_only_db(command_path: &'static str, description: &'static str) -> Self {
        Self::read_only(command_path, description).with_read_snapshot()
    }

    /// Create a derived-artifact-write effect entry.
    #[must_use]
    pub fn derived_write(
        command_path: &'static str,
        derived_paths: Vec<&'static str>,
        description: &'static str,
    ) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::DerivedArtifactWrite,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::Idempotent,
            write_surfaces: WriteSurfaces {
                db_tables: Vec::new(),
                derived_paths,
                workspace_files: Vec::new(),
            },
            mutation_contract: CommandMutationContract::derived_asset_rebuild(
                "source DB generation",
                "derived artifacts are rebuildable from FrankenSQLite source records",
            ),
            runtime_contract: CommandRuntimeContract::long_running_derived(),
            requires_read_snapshot: false,
            requires_audit: false,
            description,
        }
    }

    /// Create a durable-memory-write effect entry.
    #[must_use]
    pub fn durable_write(
        command_path: &'static str,
        db_tables: Vec<&'static str>,
        description: &'static str,
    ) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::DurableMemoryWrite,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::NonIdempotent,
            write_surfaces: WriteSurfaces {
                db_tables,
                derived_paths: Vec::new(),
                workspace_files: Vec::new(),
            },
            mutation_contract: CommandMutationContract::audited_mutation(
                "caller-provided key or generated durable record ID",
            ),
            runtime_contract: CommandRuntimeContract::transactional(),
            requires_read_snapshot: false,
            requires_audit: true,
            description,
        }
    }

    /// Create a durable write that also declares companion workspace-file surfaces.
    #[must_use]
    pub fn durable_write_with_workspace_files(
        command_path: &'static str,
        db_tables: Vec<&'static str>,
        workspace_files: Vec<&'static str>,
        description: &'static str,
    ) -> Self {
        let mut effect = Self::durable_write(command_path, db_tables, description);
        effect.write_surfaces.workspace_files = workspace_files;
        effect
    }

    /// Create an append-only durable-write effect entry.
    #[must_use]
    pub fn append_only_write(
        command_path: &'static str,
        db_tables: Vec<&'static str>,
        idempotency_key: &'static str,
        description: &'static str,
    ) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::DurableMemoryWrite,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::Idempotent,
            write_surfaces: WriteSurfaces {
                db_tables,
                derived_paths: Vec::new(),
                workspace_files: Vec::new(),
            },
            mutation_contract: CommandMutationContract::append_only(idempotency_key),
            runtime_contract: CommandRuntimeContract::transactional(),
            requires_read_snapshot: false,
            requires_audit: true,
            description,
        }
    }

    /// Create a workspace-file-write effect entry.
    #[must_use]
    pub fn workspace_file_write(
        command_path: &'static str,
        workspace_files: Vec<&'static str>,
        description: &'static str,
    ) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::WorkspaceFileWrite,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::NonIdempotent,
            write_surfaces: WriteSurfaces {
                db_tables: Vec::new(),
                derived_paths: Vec::new(),
                workspace_files,
            },
            mutation_contract: CommandMutationContract::side_path_artifact(
                "artifact path plus manifest hash",
                "no-overwrite/no-delete: existing output paths block unless the verifier proves the same manifest",
            ),
            runtime_contract: CommandRuntimeContract::side_path_artifact(),
            requires_read_snapshot: false,
            requires_audit: true,
            description,
        }
    }

    /// Create an audited external-I/O command entry.
    #[must_use]
    pub fn external_io_write(
        command_path: &'static str,
        db_tables: Vec<&'static str>,
        workspace_files: Vec<&'static str>,
        idempotency_key: &'static str,
        description: &'static str,
    ) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::ExternalIo,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::NonIdempotent,
            write_surfaces: WriteSurfaces {
                db_tables,
                derived_paths: Vec::new(),
                workspace_files,
            },
            mutation_contract: CommandMutationContract {
                side_effect_class: SideEffectClass::AuditedMutation,
                transaction_scope: Some("one audit ledger append per executed command step"),
                idempotency_key: Some(idempotency_key),
                audit_surface: Some("audit_log"),
                db_generation_effect: "advances audit log for each executed step; unchanged for dry-run or rejected unsafe steps",
                index_generation_effect: "none",
                dry_run_behavior: Some(
                    "parses the manifest and reports planned steps without executing commands or writing evidence",
                ),
                recovery_behavior: "failed steps keep evidence and audit rows; later steps are skipped unless the caller opts into continuing",
                no_overwrite_behavior: Some(
                    "no-overwrite/no-delete: evidence paths use fresh run IDs and ee never deletes partial demo evidence",
                ),
                degraded_code: None,
            },
            runtime_contract: CommandRuntimeContract {
                runtime_class: RuntimeClass::MultiStage,
                default_budget_ms: Some(120_000),
                cancellation_points: &[
                    "before_start",
                    "before_step_execute",
                    "after_step_evidence",
                    "before_audit_commit",
                ],
                partial_progress_policy: "each executed step writes evidence plus one audit row; remaining steps are skipped after the first failure unless explicitly continued",
                outcome_mapping: "success, policy_denied, usage_error, storage_error, or step failure with persisted evidence",
            },
            requires_read_snapshot: false,
            requires_audit: true,
            description,
        }
    }

    /// Create a config-write effect entry.
    #[must_use]
    pub fn config_write(
        command_path: &'static str,
        workspace_files: Vec<&'static str>,
        idempotency_key: &'static str,
        description: &'static str,
    ) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::ConfigWrite,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::Idempotent,
            write_surfaces: WriteSurfaces {
                db_tables: vec!["workspace_registry", "audit_log"],
                derived_paths: Vec::new(),
                workspace_files,
            },
            mutation_contract: CommandMutationContract::audited_mutation(idempotency_key),
            runtime_contract: CommandRuntimeContract::transactional(),
            requires_read_snapshot: false,
            requires_audit: true,
            description,
        }
    }

    /// Create a config-file-write entry that does not touch the ee database.
    #[must_use]
    pub fn config_file_write(
        command_path: &'static str,
        workspace_files: Vec<&'static str>,
        idempotency_key: &'static str,
        description: &'static str,
    ) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::ConfigWrite,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::DryRunAvailable,
            write_surfaces: WriteSurfaces {
                db_tables: Vec::new(),
                derived_paths: Vec::new(),
                workspace_files,
            },
            mutation_contract: CommandMutationContract {
                side_effect_class: SideEffectClass::SidePathArtifact,
                transaction_scope: Some("workspace config file update"),
                idempotency_key: Some(idempotency_key),
                audit_surface: None,
                db_generation_effect: "source DB generation unchanged",
                index_generation_effect: "none",
                dry_run_behavior: Some(
                    "--dry-run validates and previews config changes; no files are written",
                ),
                recovery_behavior: "partial config-file output is reported as failed, never deleted by ee, and not treated as committed configuration",
                no_overwrite_behavior: Some(
                    "no-overwrite contract preserves unrelated config keys where possible; no-delete: ee never deletes the config file",
                ),
                degraded_code: None,
            },
            runtime_contract: CommandRuntimeContract::side_path_artifact(),
            requires_read_snapshot: false,
            requires_audit: false,
            description,
        }
    }

    /// Create a harness settings-file write entry that does not touch the ee database.
    #[must_use]
    pub fn harness_hook_settings_write(
        command_path: &'static str,
        workspace_files: Vec<&'static str>,
        idempotency_key: &'static str,
        description: &'static str,
    ) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::ConfigWrite,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::DryRunAvailable,
            write_surfaces: WriteSurfaces {
                db_tables: Vec::new(),
                derived_paths: Vec::new(),
                workspace_files,
            },
            mutation_contract: CommandMutationContract {
                side_effect_class: SideEffectClass::SidePathArtifact,
                transaction_scope: Some("agent harness settings file update"),
                idempotency_key: Some(idempotency_key),
                audit_surface: None,
                db_generation_effect: "source DB generation unchanged",
                index_generation_effect: "none",
                dry_run_behavior: Some(
                    "--print previews generated harness hooks without writing settings files",
                ),
                recovery_behavior: "failed harness settings writes return storage_error, partial output is never deleted by ee, and backups are left in place for manual restore and --undo",
                no_overwrite_behavior: Some(
                    "no-overwrite/no-delete: preserves unmanaged settings entries; install writes a deterministic backup before changing managed hook entries; ee never deletes harness settings files",
                ),
                degraded_code: None,
            },
            runtime_contract: CommandRuntimeContract::side_path_artifact(),
            requires_read_snapshot: false,
            requires_audit: false,
            description,
        }
    }

    /// Create a certificate key-file write entry that does not touch the ee database.
    #[must_use]
    pub fn certificate_key_file_write(
        command_path: &'static str,
        workspace_files: Vec<&'static str>,
        idempotency_key: &'static str,
        description: &'static str,
    ) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::ConfigWrite,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::DryRunAvailable,
            write_surfaces: WriteSurfaces {
                db_tables: Vec::new(),
                derived_paths: Vec::new(),
                workspace_files,
            },
            mutation_contract: CommandMutationContract {
                side_effect_class: SideEffectClass::SidePathArtifact,
                transaction_scope: Some("key file create-or-explicit-force overwrite"),
                idempotency_key: Some(idempotency_key),
                audit_surface: None,
                db_generation_effect: "source DB generation unchanged",
                index_generation_effect: "none",
                dry_run_behavior: Some(
                    "--show reads existing key material only; no files are written",
                ),
                recovery_behavior: "partial key-file output is reported as failed, never deleted by ee, and not treated as valid key material",
                no_overwrite_behavior: Some(
                    "no-overwrite by default; --force is an explicit overwrite, and no-delete: ee never deletes key material",
                ),
                degraded_code: None,
            },
            runtime_contract: CommandRuntimeContract::side_path_artifact(),
            requires_read_snapshot: false,
            requires_audit: false,
            description,
        }
    }

    /// Create a workspace state-file write entry.
    #[must_use]
    pub fn workspace_state_write(
        command_path: &'static str,
        workspace_files: Vec<&'static str>,
        idempotency_key: &'static str,
        description: &'static str,
    ) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::WorkspaceFileWrite,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::DryRunAvailable,
            write_surfaces: WriteSurfaces {
                db_tables: Vec::new(),
                derived_paths: Vec::new(),
                workspace_files,
            },
            mutation_contract: CommandMutationContract {
                side_effect_class: SideEffectClass::AuditedMutation,
                transaction_scope: Some("workspace-local state file update"),
                idempotency_key: Some(idempotency_key),
                audit_surface: Some("workspace state file"),
                db_generation_effect: "source DB generation unchanged",
                index_generation_effect: "none",
                dry_run_behavior: Some(
                    "--dry-run previews the state transition without writing workspace files",
                ),
                recovery_behavior: "failed workspace state writes return storage_error; rerun from the last readable state file",
                no_overwrite_behavior: None,
                degraded_code: None,
            },
            runtime_contract: CommandRuntimeContract::transactional(),
            requires_read_snapshot: false,
            requires_audit: true,
            description,
        }
    }

    /// Create a durable state write backed by a non-audit-log evidence spine.
    #[must_use]
    pub fn durable_state_write(
        command_path: &'static str,
        db_tables: Vec<&'static str>,
        idempotency_key: &'static str,
        audit_surface: &'static str,
        description: &'static str,
    ) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::DurableMemoryWrite,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::DryRunAvailable,
            write_surfaces: WriteSurfaces {
                db_tables,
                derived_paths: Vec::new(),
                workspace_files: Vec::new(),
            },
            mutation_contract: CommandMutationContract {
                side_effect_class: SideEffectClass::AuditedMutation,
                transaction_scope: Some("single DB transaction across state/evidence rows"),
                idempotency_key: Some(idempotency_key),
                audit_surface: Some(audit_surface),
                db_generation_effect: "advances on commit; unchanged for dry-run or rollback",
                index_generation_effect: "none unless a downstream steward job is queued",
                dry_run_behavior: Some("validates and renders the report without writing DB rows"),
                recovery_behavior: "transaction rollback leaves no partial durable records",
                no_overwrite_behavior: None,
                degraded_code: None,
            },
            runtime_contract: CommandRuntimeContract::transactional(),
            requires_read_snapshot: false,
            requires_audit: true,
            description,
        }
    }

    /// Create the schema-migration effect entry.
    #[must_use]
    pub fn schema_migration_run() -> Self {
        Self {
            command_path: "migrate run",
            default_effect: EffectClass::DurableMemoryWrite,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::Idempotent,
            write_surfaces: WriteSurfaces {
                db_tables: vec![
                    "ee_schema_migrations",
                    "memories",
                    "search_index_jobs",
                    "audit_log",
                ],
                derived_paths: vec![".ee/index/"],
                workspace_files: Vec::new(),
            },
            mutation_contract: CommandMutationContract {
                side_effect_class: SideEffectClass::AuditedMutation,
                transaction_scope: Some(
                    "ordered schema migrations plus post-migration backfill/index audit",
                ),
                idempotency_key: Some("database path plus compiled migration checksums"),
                audit_surface: Some("ee_schema_migrations and audit_log"),
                db_generation_effect: "advances schema migration state and any migration-owned rows on commit",
                index_generation_effect: "post-migration index rebuild may refresh derived index generation",
                dry_run_behavior: Some(
                    "--dry-run reports pending migrations and backfill/index plans without mutation",
                ),
                recovery_behavior: "migration transaction rollback leaves unapplied versions pending for retry",
                no_overwrite_behavior: None,
                degraded_code: None,
            },
            runtime_contract: CommandRuntimeContract::transactional(),
            requires_read_snapshot: false,
            requires_audit: true,
            description: "Apply pending schema migrations and post-migration repair work",
        }
    }

    /// Create the shard fan-out migration effect entry.
    #[must_use]
    pub fn shard_fanout_migration() -> Self {
        Self {
            command_path: "migrate shard-fanout",
            default_effect: EffectClass::WorkspaceFileWrite,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::DryRunAvailable,
            write_surfaces: WriteSurfaces {
                db_tables: vec!["shard catalog", "workspace shard databases", "audit_log"],
                derived_paths: Vec::new(),
                workspace_files: vec![
                    "<shards-dir>/catalog.db",
                    "<shards-dir>/<workspace-shard>.db",
                    "<source-db>.pre-shard-fanout",
                ],
            },
            mutation_contract: CommandMutationContract {
                side_effect_class: SideEffectClass::AuditedMutation,
                transaction_scope: Some(
                    "preserve source database, copy workspace rows, then write shard catalog",
                ),
                idempotency_key: Some("source database hash plus shard fan-out plan"),
                audit_surface: Some("shard migration audit rows"),
                db_generation_effect: "source DB generation is preserved; shard catalog and workspace shard DBs advance",
                index_generation_effect: "none",
                dry_run_behavior: Some(
                    "--dry-run reports the shard plan and blockers without writing shard files",
                ),
                recovery_behavior: "preserved source copy and shard hashes let reruns detect already-applied work",
                no_overwrite_behavior: Some(
                    "no-overwrite/no-delete: source database is preserved before copy and existing incompatible shard/catalog hashes block apply",
                ),
                degraded_code: None,
            },
            runtime_contract: CommandRuntimeContract::side_path_artifact(),
            requires_read_snapshot: false,
            requires_audit: true,
            description: "Migrate a monolithic workspace database into per-workspace shard files",
        }
    }

    /// Create a degraded/unavailable read-only effect entry.
    #[must_use]
    pub const fn degraded_unavailable(
        command_path: &'static str,
        degraded_code: &'static str,
        description: &'static str,
    ) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::ReadOnly,
            dry_run_effect: None,
            idempotency: IdempotencyClass::Idempotent,
            write_surfaces: WriteSurfaces::none(),
            mutation_contract: CommandMutationContract::degraded_unavailable(degraded_code),
            runtime_contract: CommandRuntimeContract::immediate(),
            requires_read_snapshot: false,
            requires_audit: false,
            description,
        }
    }

    /// Create a supervised maintenance-job effect entry.
    #[must_use]
    pub fn supervised_job(
        command_path: &'static str,
        db_tables: Vec<&'static str>,
        description: &'static str,
    ) -> Self {
        Self {
            command_path,
            default_effect: EffectClass::DurableMemoryWrite,
            dry_run_effect: Some(EffectClass::ReadOnly),
            idempotency: IdempotencyClass::DryRunAvailable,
            write_surfaces: WriteSurfaces {
                db_tables,
                derived_paths: Vec::new(),
                workspace_files: Vec::new(),
            },
            mutation_contract: CommandMutationContract::supervised_jobs(
                "workspace id plus job type plus unapplied feedback set",
                "job result reports failed/skipped/cancelled work; durable changes are limited to handler-owned audited updates",
            ),
            runtime_contract: CommandRuntimeContract::supervised_jobs(),
            requires_read_snapshot: false,
            requires_audit: true,
            description,
        }
    }

    /// Override the default runtime contract for a specific command path.
    #[must_use]
    pub const fn with_runtime_contract(mut self, runtime_contract: CommandRuntimeContract) -> Self {
        self.runtime_contract = runtime_contract;
        self
    }

    /// Mark this command as requiring a read-side snapshot lease.
    #[must_use]
    pub const fn with_read_snapshot(mut self) -> Self {
        self.requires_read_snapshot = true;
        self
    }

    /// `true` if this read-only command should acquire a read-side snapshot.
    #[must_use]
    pub const fn read_snapshot(&self) -> bool {
        self.requires_read_snapshot
    }

    /// `true` if running this command is safe mid-task (no durable mutation).
    #[must_use]
    pub const fn is_safe_mid_task(&self) -> bool {
        matches!(self.default_effect, EffectClass::ReadOnly)
    }
}

/// The complete command effect manifest.
#[derive(Clone, Debug)]
pub struct EffectManifest {
    entries: HashMap<&'static str, CommandEffect>,
}

impl EffectManifest {
    /// Build the manifest from the canonical command list.
    ///
    /// Panics if any `command_path` appears in more than one of the nine
    /// category vectors. The contract is "a command must be classified
    /// in exactly one effect class"; a duplicate would mean the second
    /// category silently overwrites the first via `HashMap::insert`,
    /// and a command's declared effect would depend on the order
    /// `build()` walks the category functions. The mid-task safety
    /// classifier (`is_safe_mid_task`), the doctor capability surface,
    /// and the audit log all key off this manifest, so a silent
    /// miscategorization here would route a mutating command through a
    /// safe-read code path. The duplicate check turns that drift into a
    /// loud, immediate failure at startup.
    #[must_use]
    pub fn build() -> Self {
        let mut entries = HashMap::new();

        // Read-only commands
        for entry in Self::read_only_commands() {
            Self::insert_unique(&mut entries, entry);
        }

        // Explicitly unavailable commands that must not mutate.
        for entry in Self::degraded_unavailable_commands() {
            Self::insert_unique(&mut entries, entry);
        }

        // Derived artifact write commands
        for entry in Self::derived_write_commands() {
            Self::insert_unique(&mut entries, entry);
        }

        // Audited external command execution surfaces
        for entry in Self::external_io_write_commands() {
            Self::insert_unique(&mut entries, entry);
        }

        // Supervised steward jobs
        for entry in Self::supervised_job_commands() {
            Self::insert_unique(&mut entries, entry);
        }

        // Append-only write commands
        for entry in Self::append_only_write_commands() {
            Self::insert_unique(&mut entries, entry);
        }

        // Durable write commands
        for entry in Self::durable_write_commands() {
            Self::insert_unique(&mut entries, entry);
        }

        // Config write commands
        for entry in Self::config_write_commands() {
            Self::insert_unique(&mut entries, entry);
        }

        // Workspace file write commands
        for entry in Self::workspace_file_write_commands() {
            Self::insert_unique(&mut entries, entry);
        }

        Self { entries }
    }

    fn insert_unique(entries: &mut HashMap<&'static str, CommandEffect>, entry: CommandEffect) {
        let path = entry.command_path;
        let previous_class = entries.get(path).map(|prior| prior.default_effect);
        if entries.insert(path, entry).is_some() {
            panic!(
                "EffectManifest::build: duplicate command path `{path}` registered in two \
                 categories (previous default_effect = {previous_class:?}). A command must \
                 appear in exactly one of {{read_only, degraded_unavailable, derived_write, \
                 external_io_write, supervised_job, append_only_write, durable_write, \
                 config_write, workspace_file_write}} — the second registration would \
                 silently overwrite the first and the command's declared effect class \
                 would depend on the build()-walk order."
            );
        }
    }

    fn read_only_commands() -> Vec<CommandEffect> {
        vec![
            CommandEffect::read_only("agent detect", "Detect installed coding agents"),
            CommandEffect::read_only("agent scan", "Scan agent probe paths"),
            CommandEffect::read_only("agent sources", "List known agent source connectors"),
            CommandEffect::read_only("agent status", "Report local agent inventory status"),
            CommandEffect::read_only(
                "analyze clustering",
                "Analyze consolidation clustering posture",
            ),
            CommandEffect::read_only(
                "analyze drift",
                "Analyze drift between evaluation snapshots",
            ),
            CommandEffect::read_only("analyze science-status", "Report science readiness"),
            CommandEffect::read_only("agent-docs", "Display agent documentation"),
            CommandEffect::read_only_db("audit diff", "Show audit log mutations in a time window"),
            CommandEffect::read_only_db("audit show", "Show one audit log row"),
            CommandEffect::read_only_db("audit timeline", "List audit log rows"),
            CommandEffect::read_only_db("audit verify", "Verify audit hash-chain integrity"),
            CommandEffect::read_only_db("backup inspect", "Inspect backup manifest"),
            CommandEffect::read_only_db("backup list", "List backup manifests"),
            CommandEffect::read_only_db("backup verify", "Verify backup manifest and contents"),
            CommandEffect::read_only_db(
                "bootstrap docs",
                "Compile allowlisted workspace docs into dry-run bootstrap candidates (no durable mutation)",
            ),
            CommandEffect::read_only("capabilities", "Report feature availability"),
            CommandEffect::read_only(
                "cache hotset-manifest",
                "Collect a read-only hotset manifest from bounded coordination evidence",
            ),
            CommandEffect::read_only(
                "cache prewarm",
                "Plan explicit cache prewarm admission from a hotset manifest",
            ),
            CommandEffect::read_only_db("certificate list", "List persisted certificate records"),
            CommandEffect::read_only_db(
                "certificate show",
                "Inspect a persisted certificate record",
            ),
            CommandEffect::read_only_db(
                "certificate verify",
                "Verify persisted certificate hash and signature evidence",
            ),
            CommandEffect::read_only(
                "certificate sign",
                "Compute a certificate signature from local key material without persisting it",
            ),
            CommandEffect::read_only_db("causal trace", "Trace persisted causal evidence chains"),
            CommandEffect::read_only_db(
                "causal compare",
                "Compare persisted causal evidence chains and scoped causal evidence",
            ),
            CommandEffect::read_only_db(
                "causal estimate",
                "Estimate causal uplift from persisted or scoped causal evidence",
            ),
            CommandEffect::read_only(
                "regress explain",
                "Build a regression-causality capsule from explicit structured artifacts",
            ),
            CommandEffect::read_only("check", "Quick posture summary"),
            CommandEffect::read_only("claim list", "List executable claims from claims.yaml"),
            CommandEffect::read_only("claim show", "Inspect one executable claim"),
            CommandEffect::read_only(
                "claim verify",
                "Verify executable claim evidence without mutating source records",
            ),
            CommandEffect::read_only_db(
                "capture suggest",
                "Suggest ambient capture candidates from session evidence without durable mutation",
            ),
            CommandEffect::read_only("config get", "Read one merged config key"),
            CommandEffect::read_only("config show", "Show merged config values"),
            CommandEffect::read_only_db(
                "conflict cluster",
                "Cluster persisted contradiction/conflict evidence without mutation",
            ),
            CommandEffect::read_only_db(
                "conflict explain",
                "Explain persisted contradiction/conflict evidence",
            ),
            CommandEffect::read_only_db(
                "conflict list",
                "List persisted contradiction/conflict evidence",
            ),
            CommandEffect::read_only_db("context", "Assemble context pack (reads only)"),
            CommandEffect::read_only_db("context-show", "Show a persisted context pack"),
            CommandEffect::read_only_db(
                "decide list",
                "List durable decision memories and supersede-chain heads",
            ),
            CommandEffect::read_only_db(
                "decide revisit",
                "List due or near-due decision revisit reminders",
            ),
            CommandEffect::read_only_db("orient", "Assemble read-only agent orientation bundle"),
            CommandEffect::read_only_db(
                "orient decisions",
                "Read due decision revisit reminders for orientation output",
            ),
            CommandEffect::read_only("completion", "Generate shell completion scripts"),
            CommandEffect::read_only_db("db status", "Report database status"),
            CommandEffect::read_only_db("db check", "Check database integrity"),
            CommandEffect::read_only_db(
                "db inspect",
                "Inspect rows from one database table without mutation",
            ),
            CommandEffect::read_only_db(
                "db reindex",
                "Preview database-derived index rebuild work",
            ),
            CommandEffect::read_only_db("db migrations", "List database migrations"),
            CommandEffect::read_only_db("curate candidates", "List curation candidates"),
            CommandEffect::read_only_db(
                "curate doctor",
                "Diagnose memory debt from persisted memory state",
            ),
            CommandEffect::read_only_db(
                "health scorecard",
                "Summarize memory-store health from debt, gaps, trust, redundancy, and graph signals",
            ),
            CommandEffect::read_only_db(
                "curate show",
                "Inspect a single curation candidate read-only with apply preview",
            ),
            CommandEffect::read_only_db("curate validate", "Validate curation candidate"),
            CommandEffect::read_only("demo list", "List demo manifests"),
            CommandEffect::read_only_db("demo show", "Show persisted demo audit rows"),
            CommandEffect::read_only_db("demo verify", "Verify demo artifacts"),
            CommandEffect::read_only_db("diag advisory-lock", "Inspect advisory-lock diagnostics"),
            CommandEffect::read_only_db(
                "diag agentsmd-drift",
                "Report AGENTS.md bridge drift: stale export, file-vs-memory contradictions, missing rules",
            ),
            CommandEffect::read_only_db("diag artifacts", "Inspect artifact diagnostics"),
            CommandEffect::read_only_db(
                "diag build-admission",
                "Inspect build-admission diagnostics",
            ),
            CommandEffect::read_only_db("diag causal-edge", "Inspect causal-edge diagnostics"),
            CommandEffect::read_only_db("diag claims", "Inspect claim diagnostics"),
            CommandEffect::read_only_db("diag contention", "Inspect contention diagnostics"),
            CommandEffect::read_only_db(
                "diag curation-candidate",
                "Inspect curation-candidate diagnostics",
            ),
            CommandEffect::read_only_db("diag database-skew", "Inspect database-skew diagnostics"),
            CommandEffect::read_only_db("diag dependencies", "Inspect dependency diagnostics"),
            CommandEffect::read_only_db("diag disk-pressure", "Inspect disk-pressure diagnostics"),
            CommandEffect::read_only_db(
                "diag environment-attestation",
                "Inspect environment attestation diagnostics",
            ),
            CommandEffect::read_only_db("diag graph", "Inspect graph diagnostics"),
            CommandEffect::read_only_db(
                "diag graph-snapshot",
                "Inspect graph-snapshot diagnostics",
            ),
            CommandEffect::read_only_db("diag host-profile", "Inspect host-profile diagnostics"),
            CommandEffect::read_only_db("diag incident", "Inspect incident diagnostics"),
            CommandEffect::read_only_db("diag integrity", "Inspect storage integrity diagnostics"),
            CommandEffect::read_only_db(
                "diag memory-validity",
                "Inspect memory-validity diagnostics",
            ),
            CommandEffect::read_only_db(
                "diag model-registry",
                "Inspect model-registry diagnostics",
            ),
            CommandEffect::read_only_db("diag pack-latest", "Inspect latest pack diagnostics"),
            CommandEffect::read_only(
                "diag resource-admission",
                "Preview a resource admission decision from explicit inputs",
            ),
            CommandEffect::read_only_db("diag plan-cache", "Inspect plan-cache diagnostics"),
            CommandEffect::read_only_db(
                "diag provenance",
                "Inspect live provenance freshness diagnostics",
            ),
            CommandEffect::read_only_db("diag quarantine list", "List quarantine entries"),
            CommandEffect::read_only_db("diag quarantine show", "Show single quarantine entry"),
            CommandEffect::read_only_db("diag search", "Inspect search diagnostics"),
            CommandEffect::read_only(
                "diag store-integrity",
                "Inspect explicit read-fence and write-immune diagnostics",
            ),
            CommandEffect::read_only_db("diag streams", "Show streams status"),
            CommandEffect::read_only(
                "diag toolchain-provenance",
                "Inspect observed toolchain provenance without mutating state",
            ),
            CommandEffect::read_only_db("diag tripwire", "Inspect tripwire diagnostics"),
            CommandEffect::read_only_db("diag write-owner", "Inspect write-owner diagnostics"),
            CommandEffect::read_only_db("diag write-spool", "Inspect write-spool diagnostics"),
            CommandEffect::read_only_db("doctor", "Run health checks"),
            CommandEffect::read_only("eval list", "List evaluation scenarios"),
            CommandEffect::read_only("eval report", "Summarize evaluation fixture reports"),
            CommandEffect::read_only("eval run", "Run evaluation (reads fixtures)"),
            CommandEffect::read_only_db(
                "economy report",
                "Report DB-backed memory economy metrics without mutation",
            ),
            CommandEffect::read_only_db(
                "economy score",
                "Score one persisted memory economy artifact without mutation",
            ),
            CommandEffect::read_only_db(
                "economy simulate",
                "Simulate attention budgets from persisted economy metrics without mutation",
            ),
            CommandEffect::read_only_db(
                "economy prune-plan",
                "Plan report-only memory economy pruning without mutation",
            ),
            CommandEffect::read_only_db(
                "focus explain",
                "Explain passive active-memory focus state",
            ),
            CommandEffect::read_only_db("focus show", "Show passive active-memory focus state"),
            CommandEffect::read_only_db(
                "focus suggest",
                "Suggest focus areas from recent CASS spans and graph centrality (bd-sg5si Phase 1: schema scaffold)",
            ),
            CommandEffect::read_only_db("graph articulation", "List graph articulation points"),
            CommandEffect::read_only_db(
                "graph betweenness",
                "Compute graph betweenness centrality",
            ),
            CommandEffect::read_only_db("graph centrality", "Compute graph centrality metrics"),
            CommandEffect::read_only_db("graph communities", "Compute graph communities"),
            CommandEffect::read_only_db(
                "graph diff",
                "Temporal structural diff between two persisted graph snapshots: add/remove sets, fingerprint-matched community deltas, persisted-centrality movers (ADR 0066); never recomputes centrality inline",
            ),
            CommandEffect::read_only_db("graph explain-link", "Explain graph link evidence"),
            CommandEffect::read_only_db("graph export", "Export graph projection report"),
            CommandEffect::read_only_db("graph hits", "Compute graph HITS centrality"),
            CommandEffect::read_only_db("graph k-core", "Compute graph k-core decomposition"),
            CommandEffect::read_only_db("graph louvain", "Compute graph Louvain communities"),
            CommandEffect::read_only_db("graph neighborhood", "Inspect graph neighborhood"),
            CommandEffect::read_only_db("graph pagerank", "Compute graph PageRank scores"),
            CommandEffect::read_only_db("graph path", "Find graph shortest path"),
            CommandEffect::read_only(
                "handoff completion-audit",
                "Audit objective completion evidence without mutation",
            ),
            CommandEffect::read_only("handoff inspect", "Inspect handoff capsule"),
            CommandEffect::read_only(
                "handoff preview",
                "Plan handoff capsule contents without writing",
            ),
            CommandEffect::read_only("handoff resume", "Render handoff resume payload"),
            CommandEffect::read_only_db("artifact inspect", "Inspect artifact metadata"),
            CommandEffect::read_only_db("artifact list", "List registered artifacts"),
            CommandEffect::read_only_db(
                "attest memory",
                "Inspect memory attestation inputs and verdicts",
            ),
            CommandEffect::read_only_db(
                "attest pack",
                "Inspect context-pack attestation inputs and verdicts",
            ),
            CommandEffect::read_only_db(
                "attest query",
                "Inspect query attestation inputs and verdicts",
            ),
            CommandEffect::read_only_db("health", "Quick health check"),
            CommandEffect::read_only("help", "Print help"),
            CommandEffect::read_only_db("history", "Show persisted memory history summary"),
            CommandEffect::read_only(
                "hook git-readiness",
                "Inspect local Git hook-chain readiness without mutation",
            ),
            CommandEffect::read_only(
                "hook claude-code",
                "Print Claude Code recall/journal harness hook plan by default",
            ),
            CommandEffect::read_only(
                "hook codex",
                "Print Codex recall/journal harness hook plan by default",
            ),
            CommandEffect::read_only(
                "hook gemini",
                "Report Gemini harness hook support posture without guessing",
            ),
            CommandEffect::read_only(
                "hook status",
                "Inspect managed harness hook posture without mutating settings",
            ),
            CommandEffect::read_only_db(
                "impact",
                "Estimate impact from persisted graph and memory state",
            ),
            CommandEffect::read_only_db("index status", "Show index status"),
            CommandEffect::read_only(
                "index vacuum",
                "Preview reclaimable derived index artifacts without mutation",
            ),
            CommandEffect::read_only_db("insights", "Render persisted insight summaries"),
            CommandEffect::read_only("install check", "Inspect install posture"),
            CommandEffect::read_only("install plan", "Plan install without mutation"),
            CommandEffect::read_only("introspect", "Introspect ee metadata"),
            CommandEffect::read_only_db("job list", "List available steward job types"),
            CommandEffect::read_only_db("job show", "Show steward job row details"),
            CommandEffect::read_only(
                "lab replay",
                "Re-assembles a pack against a previously captured frozen episode and reports whether the captured inputs still produce a matching pack hash (N15.4 / bd-17c65.14.15.5)",
            ),
            CommandEffect::read_only(
                "lab counterfactual",
                "Replays a frozen episode with single-input swaps and surfaces the pack diff between the captured pack and the counterfactual pack (N15.5 / bd-17c65.14.15.6)",
            ),
            CommandEffect::read_only(
                "lab generate-workload",
                "Generate a deterministic workload report without persisting it",
            ),
            CommandEffect::read_only(
                "lab promote-workload",
                "Preview workload promotion and admission without persisting it",
            ),
            CommandEffect::read_only_db(
                "journal list",
                "List append-only journal entries newest-first",
            ),
            CommandEffect::read_only_db(
                "journal show",
                "Show one journal entry with structured sidecar and redaction report",
            ),
            CommandEffect::read_only_db(
                "ask",
                "Deterministic extractive question answering with citations and honest abstention",
            ),
            CommandEffect::read_only_db(
                "recall",
                "Code-anchored reverse lookup from paths, symbols, or a git diff to anchored memories",
            ),
            CommandEffect::read_only_db(
                "similar",
                "Find embedding-native nearest-neighbor memories for a persisted seed memory",
            ),
            CommandEffect::read_only_db(
                "learn agenda",
                "Show learning agenda with prioritized gaps",
            ),
            CommandEffect::read_only_db(
                "learn cluster",
                "Cluster learning evidence without durable mutation",
            ),
            CommandEffect::read_only_db(
                "learn gaps",
                "Mine query-miss demand into learning gap templates",
            ),
            CommandEffect::read_only_db("learn summary", "Show learning summary statistics"),
            CommandEffect::read_only_db("learn uncertainty", "Show uncertainty estimates"),
            CommandEffect::read_only_db("lens explain", "Explain a persisted lens projection"),
            CommandEffect::read_only_db("lens list", "List available persisted lens projections"),
            CommandEffect::read_only_db(
                "maintenance status",
                "Report maintenance job availability",
            ),
            CommandEffect::read_only_db("migrate status", "Report pending schema migrations"),
            CommandEffect::read_only("mcp manifest", "Inspect optional MCP adapter manifest"),
            CommandEffect::read_only("mcp validate", "Validate optional MCP adapter contracts"),
            CommandEffect::read_only_db(
                "shadow run",
                "Execute a shadowable policy evaluator offline (ADR 0070): label extraction, seeded read-only query replay, deterministic candidate sweep, report emission; writes nothing",
            ),
            CommandEffect::read_only_db("memory drift", "Report read-only memory provenance drift"),
            CommandEffect::read_only_db("memory history", "Show memory revision history"),
            CommandEffect::read_only_db("memory list", "List memories"),
            CommandEffect::read_only_db("memory show", "Show memory details"),
            CommandEffect::read_only_db(
                "mesh hello-responder",
                "Inspect mesh hello-responder status",
            ),
            CommandEffect::read_only_db("mesh init", "Preview mesh initialization state"),
            CommandEffect::read_only_db(
                "mesh ledger",
                "Inspect receiver-local mesh import decisions",
            ),
            CommandEffect::read_only_db("mesh peer list", "List mesh peers"),
            CommandEffect::read_only_db("mesh peer show", "Show one mesh peer"),
            CommandEffect::read_only_db(
                "mesh peer unknown-attempt",
                "Inspect unknown mesh-peer admission attempts",
            ),
            CommandEffect::read_only_db("mesh peers", "List mesh peers"),
            CommandEffect::read_only_db(
                "mesh preview-grant",
                "Preview a mesh sharing grant without persisting it",
            ),
            CommandEffect::read_only_db("mesh status", "Inspect mesh status"),
            CommandEffect::read_only_db("model list", "List model registry entries"),
            CommandEffect::read_only_db("model status", "Inspect model registry status"),
            CommandEffect::read_only_db("outcome quarantine list", "List feedback quarantine rows"),
            CommandEffect::read_only_db("pack diff", "Compare persisted pack ledgers"),
            CommandEffect::read_only_db("pack replay", "Inspect persisted pack ledger"),
            CommandEffect::read_only(
                "perf budget check",
                "Check normalized performance artifact budget posture",
            ),
            CommandEffect::read_only(
                "perf compare",
                "Compare normalized performance artifact summaries",
            ),
            CommandEffect::read_only(
                "perf explain-latency",
                "Explain latency stages for a normalized performance artifact",
            ),
            CommandEffect::read_only(
                "perf live",
                "Stream read-only performance snapshots for swarm observability",
            ),
            CommandEffect::read_only(
                "perf prompt-budget",
                "Estimate prompt budget posture without durable mutation",
            ),
            CommandEffect::read_only(
                "perf snapshot",
                "Emit one read-only performance snapshot for swarm observability",
            ),
            CommandEffect::read_only_db(
                "plan recipe list",
                "List built-in and stored workspace recipes",
            ),
            CommandEffect::read_only_db(
                "plan recipe show",
                "Show a built-in or stored workspace recipe",
            ),
            CommandEffect::read_only(
                "preflight show",
                "Read a persisted preflight run from the workspace-local store",
            ),
            CommandEffect::read_only_db(
                "preflight check",
                "Retrieve advisory command-risk memories without granting or revoking execution authority",
            ),
            CommandEffect::read_only_db(
                "preflight guard",
                "Alias for read-only advisory command-risk memory retrieval",
            ),
            CommandEffect::read_only("plan goal", "Recommends recipes for goals"),
            CommandEffect::read_only_db(
                "plan explain",
                "Explains recipe provenance and applicability",
            ),
            CommandEffect::read_only("plan recommend", "Recommends recipes for tasks"),
            CommandEffect::read_only_db("playbook list", "List procedural rules in playbook form"),
            CommandEffect::read_only_db(
                "procedure drift",
                "Inspect procedure maturity and feedback drift signals",
            ),
            CommandEffect::read_only_db(
                "procedure export",
                "Render a persisted procedure artifact",
            ),
            CommandEffect::read_only_db("procedure list", "List persisted procedures"),
            CommandEffect::read_only_db("procedure show", "Show persisted procedure details"),
            CommandEffect::read_only_db(
                "procedure verify",
                "Verify a persisted procedure against evidence sources",
            ),
            CommandEffect::read_only_db("rationale list", "List safe rationale traces"),
            CommandEffect::read_only_db("rationale show", "Show a safe rationale trace"),
            CommandEffect::read_only_db(
                "reflect request-ledger diagnostics",
                "Inspect reflection request ledger diagnostics without exposing secret payloads",
            ),
            CommandEffect::read_only(
                "profile config plan",
                "Plan operating profile configuration without writing files",
            ),
            CommandEffect::read_only_db("proof admit", "Preview proof admission status"),
            CommandEffect::read_only_db("proof status", "Inspect proof status"),
            CommandEffect::read_only_db(
                "proximity",
                "Compute memory proximity from persisted graph state",
            ),
            CommandEffect::read_only(
                "recorder tail",
                "Recorder tail reads persisted recorder events without mutation",
            ),
            CommandEffect::read_only(
                "recorder follow",
                "Recorder follow streams persisted recorder events without mutation",
            ),
            CommandEffect::read_only(
                "recorder import",
                "Recorder import planning is read-only unless explicitly promoted to execution",
            ),
            CommandEffect::read_only(
                "recorder events list",
                "List persisted recorder events without mutation",
            ),
            CommandEffect::read_only(
                "recorder flight replay",
                "Replay a flight-recorder trace without mutating source state",
            ),
            CommandEffect::read_only(
                "rehearse plan",
                "Rehearsal planning validates command specs and estimates side-path artifacts",
            ),
            CommandEffect::read_only(
                "rehearse inspect",
                "Rehearsal inspection reads a prior manifest and verifies hashes",
            ),
            CommandEffect::read_only(
                "rehearse promote-plan",
                "Rehearsal promotion planning reads a manifest and emits a conservative checklist",
            ),
            CommandEffect::read_only(
                "review session",
                "Analyze session evidence spans for curation candidates",
            ),
            CommandEffect::read_only_db(
                "resume",
                "Assemble the session-resume bundle: recent episodic sessions, revisit-conditioned decisions, queued-tag items, staleness flags, nearby stores (reads only)",
            ),
            CommandEffect::read_only(
                "sandbox diff",
                "Compare sandbox state with workspace state without applying changes",
            ),
            CommandEffect::read_only_db("rule list", "List procedural rules"),
            CommandEffect::read_only_db(
                "rule provenance",
                "Inspect the rule-to-memory provenance ego graph",
            ),
            CommandEffect::read_only_db("rule show", "Show procedural rule"),
            CommandEffect::read_only("schema export", "Export public response schemas"),
            CommandEffect::read_only("schema list", "List response schemas"),
            CommandEffect::read_only_db("search", "Search memories"),
            CommandEffect::read_only_db(
                "search --all-workspaces",
                "Read-only diagnostic: run one query across every workspace registered in the addressed database plus the global lane, rows labeled per workspace; inspection surface, never a pack input",
            ),
            CommandEffect::read_only_db(
                "sentinel explain",
                "Explain sentinel specifications and prior results",
            ),
            CommandEffect::read_only_db(
                "share preview",
                "Preview outbound mesh sharing without exporting data",
            ),
            CommandEffect::read_only_db("show", "Show a persisted memory or artifact"),
            CommandEffect::read_only(
                "situation classify",
                "Classify task into situation category",
            ),
            CommandEffect::read_only("situation compare", "Compare two situations (dry-run)"),
            CommandEffect::read_only_db("situation explain", "Explain a stored situation"),
            CommandEffect::read_only("situation link", "Plan situation link (dry-run)"),
            CommandEffect::read_only_db("situation show", "Show stored situation details"),
            CommandEffect::read_only_db("status", "Report workspace status"),
            CommandEffect::read_only_db("subscribe poll", "Poll subscription state"),
            CommandEffect::read_only_db(
                "subscribe stream",
                "Stream subscription state without writing durable records",
            ),
            CommandEffect::read_only(
                "support inspect",
                "Verify and inspect a redacted support bundle manifest",
            ),
            CommandEffect::read_only(
                "session-budget plan",
                "Advisory deterministic plan for cheapest useful next command given ledger and posture",
            ),
            CommandEffect::read_only_db("swarm brief", "Report read-only swarm coordination brief"),
            CommandEffect::read_only_db(
                "swarm next-action",
                "Recommend the next swarm action without claiming work",
            ),
            CommandEffect::read_only_db(
                "swarm repair-plan",
                "Render an advisory degraded-stack repair plan without executing repairs",
            ),
            CommandEffect::read_only_db(
                "swarm work-packet",
                "Render a swarm work packet without mutating coordination state",
            ),
            CommandEffect::read_only_db("task-frame show", "Show passive task-frame state"),
            CommandEffect::read_only_db(
                "team port show",
                "Report the folded team hello port and genesis hash without mutation",
            ),
            CommandEffect::read_only_db(
                "timeline",
                "Reconstruct read-only memory state for a topic at a historical timestamp",
            ),
            CommandEffect::read_only_db(
                "trust report",
                "Audit confidence calibration and outcome-backed reliability",
            ),
            CommandEffect::read_only_db("tripwire list", "List persisted tripwire rules"),
            CommandEffect::read_only("update", "Plan update without mutation"),
            CommandEffect::read_only_db(
                "verification broker lookup",
                "Look up verification broker state",
            ),
            CommandEffect::read_only_db(
                "verification closeout capsule",
                "Render a verification closeout capsule",
            ),
            CommandEffect::read_only_db(
                "verification closure-guidance",
                "Render verification closure guidance",
            ),
            CommandEffect::read_only_db("verification proofs", "List verification proofs"),
            CommandEffect::read_only_db(
                "verification rch blockers",
                "List RCH verification blockers",
            ),
            CommandEffect::read_only_db("verification rch runs", "List RCH verification runs"),
            CommandEffect::read_only_db(
                "verification rch topology-audit",
                "Audit RCH topology closure for path-dep and crate-graph gaps",
            ),
            CommandEffect::read_only_db(
                "verify broker lookup",
                "Look up verification broker state",
            ),
            CommandEffect::read_only_db(
                "verify closeout capsule",
                "Render a verification closeout capsule",
            ),
            CommandEffect::read_only_db(
                "verify closure-guidance",
                "Render verification closure guidance",
            ),
            CommandEffect::read_only_db("verify proofs", "List verification proofs"),
            CommandEffect::read_only_db("verify rch blockers", "List RCH verification blockers"),
            CommandEffect::read_only_db("verify rch runs", "List RCH verification runs"),
            CommandEffect::read_only_db(
                "verify rch topology-audit",
                "Audit RCH topology closure for path-dep and crate-graph gaps",
            ),
            CommandEffect::read_only("version", "Print version"),
            CommandEffect::read_only_db(
                "workspace hygiene",
                "Inspect workspace hygiene and coordination state",
            ),
            CommandEffect::read_only("workspace list", "List workspace aliases"),
            CommandEffect::read_only("workspace resolve", "Resolve workspace identity"),
            CommandEffect::read_only_db("why", "Explain memory selection"),
            CommandEffect::read_only_db("why-not", "Explain why a memory was not selected"),
        ]
    }

    fn derived_write_commands() -> Vec<CommandEffect> {
        vec![
            CommandEffect::derived_write(
                "index rebuild",
                vec![".ee/index/"],
                "Rebuild search indexes from database",
            ),
            CommandEffect::derived_write(
                "primer",
                vec!["primer_cache (db table)"],
                "Assemble the cached workspace primer; cache rows are derived and rebuildable (--no-persist is read-only)",
            ),
            CommandEffect::derived_write(
                "index reembed",
                vec![".ee/index/embeddings/"],
                "Rebuild semantic embeddings from database records",
            ),
            CommandEffect::derived_write(
                "search --recalibrate-now",
                vec![".ee/search/calibration.jsonl"],
                "Rewrite the derived search score calibration artifact from persisted feedback",
            ),
            CommandEffect::derived_write(
                "graph centrality-refresh",
                vec![".ee/graph/"],
                "Refresh derived graph centrality metrics",
            ),
            CommandEffect::derived_write(
                "graph feature-enrichment",
                vec![".ee/graph/"],
                "Refresh derived graph feature enrichments",
            ),
            CommandEffect::derived_write(
                "graph snapshot refresh",
                vec![".ee/graph/"],
                "Refresh derived graph snapshots from source database state",
            ),
        ]
    }

    fn degraded_unavailable_commands() -> Vec<CommandEffect> {
        Vec::new()
    }

    fn daemon_command_effect() -> CommandEffect {
        let mut effect = CommandEffect::external_io_write(
            "daemon",
            vec!["memories", "feedback_events", "audit_log"],
            vec![
                "$XDG_RUNTIME_DIR/ee/daemon.sock or ${TMPDIR:-/tmp}/ee-<uid>/daemon.sock",
                ".ee/daemon-jobs.jsonl",
            ],
            "daemon subcommand plus socket path plus workspace plus job type",
            "Run daemon status, foreground steward jobs, background steward scheduling, or UDS hot-mode lifecycle operations",
        );
        effect.idempotency = IdempotencyClass::DryRunAvailable;
        effect.dry_run_effect = Some(EffectClass::WorkspaceFileWrite);
        effect.mutation_contract = CommandMutationContract {
            side_effect_class: SideEffectClass::Mixed,
            transaction_scope: Some("daemon subcommand-specific operation"),
            idempotency_key: Some(
                "daemon subcommand plus socket path plus workspace plus job type",
            ),
            audit_surface: Some(
                "daemon job ledger or audit_log when a selected subcommand mutates",
            ),
            db_generation_effect: "subcommand-specific: status is read-only; foreground jobs may advance handler-owned state",
            index_generation_effect: "subcommand-specific: unchanged unless a selected steward job processes index work",
            dry_run_behavior: Some(
                "foreground --dry-run records planned daemon job rows and reports handler plans without committing handler mutations",
            ),
            recovery_behavior: "foreground and background job rows are persisted and recovered on restart",
            no_overwrite_behavior: Some(
                "daemon socket paths are guarded by same-UID socket checks; stop refuses regular files and stale unauthenticated sockets",
            ),
            degraded_code: None,
        };
        effect.runtime_contract = CommandRuntimeContract {
            runtime_class: RuntimeClass::MultiStage,
            default_budget_ms: Some(300_000),
            cancellation_points: &[
                "before_daemon_mode_dispatch",
                "before_socket_publish_or_probe",
                "before_foreground_job_schedule",
                "before_steward_handler",
                "before_daemon_job_row_commit",
            ],
            partial_progress_policy: "option-specific: status is read-only; foreground jobs persist planned rows before handler execution and terminal rows after completion",
            outcome_mapping: "success, usage_error, storage_error, policy_denied, or supervised job failure",
        };
        effect
    }

    fn external_io_write_commands() -> Vec<CommandEffect> {
        vec![
            Self::daemon_command_effect(),
            CommandEffect::external_io_write(
                "demo run",
                vec!["audit_log"],
                vec![
                    "demo evidence root",
                    "manifest-declared demo artifact paths",
                ],
                "demo id plus manifest hash plus generated run id",
                "Execute safe demo manifest steps with audit ledger rows and evidence artifacts",
            ),
            CommandEffect::external_io_write(
                "lab swarm replay",
                vec!["audit_log"],
                vec![".ee/lab/swarm-replay/"],
                "workload id plus replay host profile plus generated run id",
                "Replay a swarm workload through subprocess execution and write replay evidence artifacts",
            ),
            CommandEffect::external_io_write(
                "mcp serve-stdio",
                Vec::new(),
                vec!["stdio JSON-RPC stream"],
                "process id plus stdio session",
                "Serve the optional MCP stdio adapter over process I/O",
            ),
            CommandEffect::external_io_write(
                "mesh auto-enroll",
                vec!["mesh_peers", "audit_log"],
                vec![
                    ".ee/auto_enroll_overrides.toml",
                    ".ee/discovery_denylist.toml",
                ],
                "tailscale peer set hash plus workspace id",
                "Probe mesh peers and persist reviewed auto-enrollment state",
            ),
            CommandEffect::external_io_write(
                "mesh hello-responder register",
                Vec::new(),
                vec!["user-scoped mesh-responder control socket"],
                "request nonce plus team id plus workspace id plus peer handle",
                "Register exact team routes with the same-EUID user-scoped responder owner",
            ),
            CommandEffect::external_io_write(
                "mesh hello-responder run",
                Vec::new(),
                vec![
                    "verified Tailscale listener",
                    "user-scoped mesh-responder control socket",
                ],
                "process id plus committed port plus control socket path",
                "Own the user-scoped Tailscale responder listener and same-EUID control channel",
            ),
            CommandEffect::external_io_write(
                "mesh hello-responder unregister",
                Vec::new(),
                vec!["user-scoped mesh-responder control socket"],
                "request nonce plus team id plus workspace id plus peer handle",
                "Remove exact team routes from the same-EUID user-scoped responder owner",
            ),
            CommandEffect::external_io_write(
                "model fetch",
                vec!["model_registry", "audit_log"],
                vec!["~/.local/share/ee/models/"],
                "model alias plus artifact content hash",
                "Fetch or import a model artifact and update the model registry",
            ),
            CommandEffect::external_io_write(
                "serve",
                Vec::new(),
                vec!["localhost HTTP/SSE listener"],
                "process id plus listener address",
                "Serve the optional localhost adapter",
            ),
        ]
    }

    fn supervised_job_commands() -> Vec<CommandEffect> {
        vec![
            CommandEffect::supervised_job(
                "daemon foreground decay_sweep",
                vec!["memories", "feedback_events", "audit_log"],
                "Run the real score-decay steward handler in a bounded foreground daemon tick",
            ),
            CommandEffect::supervised_job(
                "daemon background",
                vec!["memories", "feedback_events", "audit_log"],
                "Run configured steward handlers on the daemon background scheduler",
            ),
            CommandEffect::supervised_job(
                "daemon foreground non-decay",
                vec!["memories", "feedback_events", "audit_log"],
                "Run real non-decay steward handlers in a bounded foreground daemon tick",
            ),
            CommandEffect::supervised_job(
                "job run",
                vec!["memories", "feedback_events", "audit_log"],
                "Run a steward job directly through the job interface",
            ),
            CommandEffect::supervised_job(
                "maintenance run",
                vec!["memories", "feedback_events", "audit_log"],
                "Run an explicit bounded maintenance job through the steward backend",
            ),
            CommandEffect::supervised_job(
                "maintenance graph-snapshot-prune",
                vec!["graph_snapshots", "audit_log"],
                "Prune expired graph snapshots through a bounded steward job",
            ),
        ]
    }

    fn append_only_write_commands() -> Vec<CommandEffect> {
        let diag_pack_record = CommandEffect::append_only_write(
            "diag pack-record",
            vec!["pack_records", "audit_log"],
            "pack id",
            "Append one audited diagnostic pack record without overwriting an existing ID",
        );
        vec![
            diag_pack_record,
            CommandEffect::append_only_write(
                "db check-integrity",
                vec!["audit_log"],
                "audit row id",
                "Run full database integrity verification and append an audit row",
            ),
            CommandEffect::append_only_write(
                "artifact register",
                vec!["artifacts", "artifact_links", "audit_log"],
                "content hash",
                "Register artifact metadata keyed by content hash",
            ),
            CommandEffect::append_only_write(
                "import cass",
                vec!["memories", "audit_log"],
                "source hash",
                "Import from CASS sessions",
            ),
            CommandEffect::append_only_write(
                "import jsonl",
                vec!["memories", "audit_log"],
                "source hash",
                "Import from JSONL export",
            ),
            CommandEffect::append_only_write(
                "import eidetic-legacy",
                vec!["memories", "audit_log"],
                "source hash",
                "Import from legacy Eidetic export",
            ),
            CommandEffect::append_only_write(
                "import agentsmd",
                vec![
                    "curation_candidates",
                    "evidence_spans",
                    "sessions",
                    "audit_log",
                ],
                "deterministic candidate id over (file, statement text)",
                "Import rule-like AGENTS.md statements as pending curation candidates",
            ),
            CommandEffect::append_only_write(
                "pack build",
                vec!["context_packs", "pack_items", "audit_log"],
                "pack hash",
                "Persist a context pack keyed by deterministic pack hash",
            ),
            CommandEffect::append_only_write(
                "reflect propose",
                vec!["reflection_request_ledger"],
                "requestHash",
                "Create an external reflection request artifact and non-secret replay ledger row",
            ),
            CommandEffect::append_only_write(
                "mesh import",
                vec!["mesh_peers", "mesh_import_ledger", "search_index_jobs"],
                "origin peer cursor plus event content hash",
                "Import a mesh artifact by replaying idempotent peer events",
            ),
            // Honest classification (bd-6dmhw): the production sync transport
            // is a deliberate no-op until M1 real transport lands
            // (bd-tc-epic-qzk7o.3.x); the command performs no peer network
            // I/O today. Restore external_io_write with the transport.
            CommandEffect::append_only_write(
                "mesh sync",
                vec!["mesh_peers", "mesh_import_ledger", "search_index_jobs"],
                "origin peer cursor plus event content hash",
                "Run one foreground sync cycle over locally available peer state; network transport is deferred",
            ),
            CommandEffect::append_only_write(
                "verification ingest",
                vec!["audit_log"],
                "verification evidence content hash",
                "Ingest verification evidence into the audit ledger",
            ),
            CommandEffect::append_only_write(
                "verification rch ingest",
                vec!["rch_verify_runs"],
                "rch proof command hash plus run id",
                "Ingest RCH verification run evidence",
            ),
            CommandEffect::append_only_write(
                "verification record",
                vec!["audit_log"],
                "verification record content hash",
                "Record verification evidence in the audit ledger",
            ),
            CommandEffect::append_only_write(
                "verify ingest",
                vec!["audit_log"],
                "verification evidence content hash",
                "Ingest verification evidence into the audit ledger",
            ),
            CommandEffect::append_only_write(
                "verify rch ingest",
                vec!["rch_verify_runs"],
                "rch proof command hash plus run id",
                "Ingest RCH verification run evidence",
            ),
            CommandEffect::append_only_write(
                "verify record",
                vec!["audit_log"],
                "verification record content hash",
                "Record verification evidence in the audit ledger",
            ),
        ]
    }

    fn durable_write_commands() -> Vec<CommandEffect> {
        vec![
            CommandEffect::durable_write(
                "graph suggest-links",
                vec!["curation_candidates"],
                "Predict missing memory links with bounded, typed, explained blended scoring (ADR 0066); default is a read-only report, --propose writes link/contradiction-review curation candidates (dedup on re-propose), never links directly",
            ),
            CommandEffect::durable_write(
                "conflict resolve",
                vec![
                    "memories",
                    "memory_links",
                    "memory_tags",
                    "search_index_jobs",
                    "audit_log",
                ],
                "Resolve one live conflict pair via verb-mapped EXISTING audited atoms (decide record / memory expire / memory link / memory tags); dry-run plan by default, --apply executes (ADR 0066)",
            ),
            CommandEffect::durable_write(
                "diagnose-error",
                vec!["error_fingerprints"],
                "Diagnose a tool error against the fingerprint recall store; --record persists its fingerprint",
            ),
            CommandEffect::durable_write(
                "bootstrap apply",
                vec![
                    "curation_candidates",
                    "memories",
                    "procedural_rules",
                    "rule_source_memories",
                    "rule_tags",
                    "search_index_jobs",
                    "audit_log",
                ],
                "Apply an approved docs bootstrap run through curation (routes through curate apply with audit)",
            ),
            CommandEffect::durable_write(
                "causal promote-plan",
                vec!["curation_candidates", "audit_log"],
                "Plan causal promotion and persist reviewed curation candidates when evidence clears thresholds",
            ),
            CommandEffect::durable_write(
                "curate accept",
                vec!["curation_candidates", "procedural_rules", "audit_log"],
                "Accept a curation candidate",
            ),
            CommandEffect::durable_write(
                "curate auto-promote",
                vec!["memories", "search_index_jobs", "audit_log"],
                "Threshold-based memory level promotion; dry-run by default, --apply routes through memory.level_transition",
            ),
            CommandEffect::durable_write(
                "curate apply",
                vec![
                    "curation_candidates",
                    "plan_recipes",
                    "memories",
                    "procedural_rules",
                    "rule_source_memories",
                    "rule_tags",
                    "search_index_jobs",
                    "audit_log",
                ],
                "Apply a curation candidate",
            ),
            CommandEffect::durable_write(
                "curate disposition",
                vec!["curation_candidates", "audit_log"],
                "Record curation disposition",
            ),
            CommandEffect::durable_write(
                "curate merge",
                vec!["curation_candidates", "memories", "audit_log"],
                "Merge curation candidates",
            ),
            CommandEffect::durable_write(
                "curate propose-derived",
                vec!["curation_candidates", "audit_log"],
                "Persist derived curation proposals for explicit review",
            ),
            CommandEffect::durable_write(
                "curate reject",
                vec!["curation_candidates", "audit_log"],
                "Reject a curation candidate",
            ),
            CommandEffect::durable_write(
                "curate retire",
                vec![
                    "curation_candidates",
                    "memories",
                    "search_index_jobs",
                    "audit_log",
                ],
                "Retire an accepted curation artifact through audited memory/index updates",
            ),
            CommandEffect::durable_write(
                "curate snooze",
                vec!["curation_candidates", "audit_log"],
                "Snooze a curation candidate",
            ),
            CommandEffect::durable_write(
                "curate tombstone",
                vec![
                    "curation_candidates",
                    "memories",
                    "search_index_jobs",
                    "audit_log",
                ],
                "Tombstone a curation candidate and related memory state without deleting records",
            ),
            CommandEffect::durable_write(
                "curate untombstone",
                vec![
                    "curation_candidates",
                    "memories",
                    "search_index_jobs",
                    "audit_log",
                ],
                "Restore a tombstoned curation candidate through audited memory/index updates",
            ),
            CommandEffect::durable_write_with_workspace_files(
                "handoff rotate-key",
                vec!["audit_log"],
                vec!["<handoff capsule path>"],
                "Rotate a handoff capsule HMAC key and rewrite the signed capsule body",
            ),
            CommandEffect {
                command_path: "health scorecard --record-snapshot",
                default_effect: EffectClass::DurableMemoryWrite,
                dry_run_effect: Some(EffectClass::ReadOnly),
                idempotency: IdempotencyClass::Idempotent,
                write_surfaces: WriteSurfaces {
                    db_tables: vec!["debt_snapshots"],
                    derived_paths: Vec::new(),
                    workspace_files: Vec::new(),
                },
                mutation_contract: CommandMutationContract {
                    side_effect_class: SideEffectClass::AuditedMutation,
                    transaction_scope: Some("single DB insert-or-ignore for memory debt snapshot"),
                    idempotency_key: Some("workspace id plus snapshot day plus generation"),
                    audit_surface: Some("debt_snapshots"),
                    db_generation_effect: "advances only when a new debt snapshot row commits; unchanged on duplicate",
                    index_generation_effect: "none",
                    dry_run_behavior: Some(
                        "omit --record-snapshot to render the same scorecard without writing debt_snapshots",
                    ),
                    recovery_behavior: "insert-or-ignore leaves at most one complete snapshot row per workspace/day/generation",
                    no_overwrite_behavior: None,
                    degraded_code: None,
                },
                runtime_contract: CommandRuntimeContract::transactional(),
                requires_read_snapshot: false,
                requires_audit: true,
                description: "Record a memory-debt trend snapshot before rendering the health scorecard",
            },
            CommandEffect::durable_write(
                "playbook extract",
                vec!["curation_candidates", "audit_log"],
                "Extract procedural-rule candidates from repeated semantic memories",
            ),
            CommandEffect::durable_write(
                "playbook import",
                vec![
                    "procedural_rules",
                    "rule_source_memories",
                    "rule_tags",
                    "search_index_jobs",
                    "audit_log",
                ],
                "Import portable playbook rules through audited procedural-rule writes",
            ),
            CommandEffect::durable_write(
                "journal append",
                vec!["journal_entries"],
                "Append a redaction-screened observation to the agent journal",
            ),
            CommandEffect::durable_write(
                "journal distill",
                vec![
                    "journal_entries",
                    "curation_candidates",
                    "evidence_spans",
                    "sessions",
                    "audit_log",
                ],
                "Distill journal entries into pending curation candidates; dry-run by default, --apply writes",
            ),
            CommandEffect::durable_write(
                "learn close",
                vec!["learning_experiments", "audit_log"],
                "Close a learning experiment",
            ),
            CommandEffect::durable_write(
                "learn experiment run",
                vec!["learning_experiments", "evaluation_reports", "audit_log"],
                "Record a learning experiment run",
            ),
            CommandEffect::durable_write(
                "learn observe",
                vec!["learning_observations", "audit_log"],
                "Record a learning observation",
            ),
            CommandEffect::durable_write(
                "learn experiment propose",
                vec!["curation_candidates", "audit_log"],
                "Persist experiment proposals to curation queue",
            ),
            CommandEffect::durable_write(
                "outcome",
                vec!["feedback_events", "audit_log"],
                "Record observed outcome feedback",
            ),
            CommandEffect::durable_write(
                "procedure promote",
                vec!["procedures", "procedure_events", "audit_log"],
                "Promote a persisted procedure maturity level",
            ),
            CommandEffect::durable_write(
                "procedure propose",
                vec!["procedures", "procedure_events", "audit_log"],
                "Persist a procedure candidate from explicit evidence",
            ),
            CommandEffect::durable_write(
                "procedure retire",
                vec!["procedures", "procedure_events", "audit_log"],
                "Retire a persisted procedure with an audited reason",
            ),
            CommandEffect::durable_write(
                "outcome quarantine release",
                vec!["feedback_quarantine", "audit_log"],
                "Release feedback from quarantine",
            ),
            CommandEffect::durable_write(
                "rationale attach",
                vec!["rationale_traces", "audit_log"],
                "Attach a safe rationale trace with audit provenance",
            ),
            CommandEffect::durable_write(
                "remember",
                vec!["memories", "memory_tags", "audit_log"],
                "Store a new memory with direct or audit-lane-backed audit_log provenance",
            ),
            CommandEffect::durable_write(
                "plan recipe save",
                vec!["plan_recipes", "audit_log"],
                "Save explicit instructions as an audited draft recipe without execution",
            ),
            CommandEffect::durable_write(
                "decide record",
                vec![
                    "memories",
                    "memory_tags",
                    "memory_links",
                    "search_index_jobs",
                    "audit_log",
                ],
                "Record a durable decision memory and optionally supersede the prior decision head",
            ),
            CommandEffect::durable_write(
                "memory revise",
                vec!["memories", "search_index_jobs", "audit_log"],
                "Inserts a new memory row with the same logical_id as the original, sets the prior row's valid_to, emits a memory.revise audit entry, atomically enqueues the new live row in search_index_jobs, then reconciles that durable job post-commit with truthful immediate-or-queued status (N15.2 / bd-17c65.14.15.3 / bd-index-auto-freshness-m5kwf)",
            ),
            CommandEffect::durable_write(
                "memory expire",
                vec!["memories", "search_index_jobs", "audit_log"],
                "Expire a memory through an audited tombstone without deleting data",
            ),
            CommandEffect::durable_write(
                "memory reveal",
                vec!["memories", "memory_seals", "search_index_jobs", "audit_log"],
                "Verify supplied bytes against a sealed memory's commitment; on match publish the content through the revise path, mark the seal revealed, and audit memory.reveal — a mismatch mutates nothing and audits memory.reveal_failed (bd-sealed-preregistration-memory-b67be)",
            ),
            CommandEffect::durable_write(
                "shadow promote",
                vec!["workspace_config", "audit_log"],
                "Apply the persisted promotable tuning report's [search] fusion-weight overlay to <workspace>/.ee/config.toml via toml_edit, recording the full prior config bytes in the promotion audit; refusals (missing/stale/abstained/non-promotable report) are typed exit-7 policy denials and dry-run writes nothing (ADR 0070 §5)",
            ),
            CommandEffect::durable_write(
                "shadow demote",
                vec!["workspace_config", "audit_log"],
                "Restore the pre-promotion config.toml bytes from the promotion audit (byte-identical; an absent prior restores as empty, never a deletion) and record the demotion",
            ),
            CommandEffect::durable_write(
                "memory promote-global",
                vec!["memories", "audit_log"],
                "Promote a workspace memory into the user-global store through the bd-1bfwa.2 policy core (evidence gate, secret re-screen, duplicate merge); refusals are typed exit-7 policy denials and dry-run writes nothing",
            ),
            CommandEffect::durable_write(
                "memory demote-global",
                vec!["memories", "audit_log"],
                "Tombstone a promoted user-global memory (withdraw the global copy without touching the origin workspace row), origin parsed from promotion provenance",
            ),
            CommandEffect::durable_write(
                "memory outcome-global",
                vec!["memories", "audit_log"],
                "Record helpful/harmful feedback on a user-global memory and backflow a clamped confidence adjustment to the origin workspace row (bd-1bfwa.2 engine); dry-run writes nothing",
            ),
            CommandEffect::durable_write(
                "memory level",
                vec!["memories", "search_index_jobs", "audit_log"],
                "Apply a canonical manual memory-level transition with audit provenance",
            ),
            CommandEffect::durable_write(
                "memory link",
                vec!["memory_links", "audit_log"],
                "List or create explicit memory links with deterministic idempotent audits",
            ),
            CommandEffect::durable_write(
                "memory tags",
                vec!["memory_tags", "search_index_jobs", "audit_log"],
                "List or mutate memory tags with deterministic idempotent audits",
            ),
            CommandEffect::durable_write(
                "link",
                vec!["memory_links", "audit_log"],
                "Create or inspect explicit memory links with audited mutation when requested",
            ),
            CommandEffect::durable_state_write(
                "maintenance wal-checkpoint",
                vec!["database_wal"],
                "database path plus checkpoint mode",
                "database WAL checkpoint",
                "Checkpoint the workspace database WAL without changing logical memory records",
            ),
            CommandEffect::durable_write_with_workspace_files(
                "mesh discovery-policy",
                vec!["audit_log"],
                vec![
                    ".ee/discovery_policy.toml",
                    ".ee/discovery_allowlist.toml",
                    ".ee/discovery_denylist.toml",
                ],
                "Persist mesh discovery policy files and audit the policy change",
            ),
            CommandEffect::durable_write_with_workspace_files(
                "mesh export",
                vec!["audit_log"],
                vec!["<--out path>"],
                "Export authorized mesh material to an explicit side-path artifact",
            ),
            CommandEffect::durable_write(
                "mesh peer add",
                vec!["mesh_peers", "audit_log"],
                "Add a mesh peer with audited policy metadata",
            ),
            CommandEffect::durable_write(
                "mesh peer revoke",
                vec!["mesh_peers", "audit_log"],
                "Revoke a mesh peer with audited policy metadata",
            ),
            CommandEffect::durable_write(
                "mesh peer rotate",
                vec!["mesh_peers", "audit_log"],
                "Rotate mesh peer credentials with audited policy metadata",
            ),
            CommandEffect::durable_write(
                "mesh grant",
                vec!["mesh_lane_grant_states", "audit_log"],
                "Apply an authenticated mesh lane consent grant with generation fencing and audit provenance",
            ),
            CommandEffect::durable_write(
                "mesh revoke-lane",
                vec!["mesh_lane_grant_states", "audit_log"],
                "Narrow mesh lane consent with generation fencing and audit provenance",
            ),
            CommandEffect::durable_write(
                "note",
                vec!["memories", "memory_tags", "audit_log"],
                "Store a note as a memory with optional tags",
            ),
            CommandEffect::durable_write(
                "reflect ingest",
                vec![
                    "reflection_request_ledger",
                    "curation_candidates",
                    "audit_log",
                ],
                "Ingest reflection evidence and propose reviewed curation candidates",
            ),
            CommandEffect::durable_write(
                "review workspace",
                vec!["curation_candidates", "audit_log"],
                "Review workspace evidence and persist curation candidates",
            ),
            CommandEffect::durable_write_with_workspace_files(
                "sandbox apply",
                vec!["memories", "memory_tags", "audit_log"],
                vec![".ee/sandbox/<session>.json"],
                "Apply reviewed sandbox memories and record sandbox session state",
            ),
            CommandEffect::durable_state_write(
                "sentinel check",
                vec!["memory_sentinel_results"],
                "sentinel spec hash plus observed result hash",
                "memory sentinel results",
                "Evaluate sentinel specs and persist checked results",
            ),
            CommandEffect::durable_write(
                "tag",
                vec!["memory_tags", "search_index_jobs", "audit_log"],
                "Add or remove memory tags through audited metadata updates",
            ),
            CommandEffect::durable_write(
                "team port migrate",
                vec!["mesh_origin_events", "mesh_peers"],
                "Append a versioned teamPortMigrated origin event and rewrite enrolled peer locators without touching pair keys or grants",
            ),
            CommandEffect::durable_write(
                "verification provenance",
                vec!["memories", "curation_candidates", "audit_log"],
                "Verify provenance and persist reviewed revalidation candidates",
            ),
            CommandEffect::durable_write(
                "verify provenance",
                vec!["memories", "curation_candidates", "audit_log"],
                "Verify provenance and persist reviewed revalidation candidates",
            ),
            CommandEffect::durable_state_write(
                "recorder start",
                vec!["recorder_runs"],
                "generated recorder run id",
                "recorder run store",
                "Persist a recorder run start row",
            ),
            CommandEffect::durable_state_write(
                "recorder event",
                vec!["recorder_events"],
                "run id plus next recorder sequence",
                "recorder event spine",
                "Append a redacted recorder event row",
            ),
            CommandEffect::durable_state_write(
                "recorder finish",
                vec!["recorder_runs"],
                "recorder run id",
                "recorder run store",
                "Mark a recorder run finished and persist rolled-up counts",
            ),
            CommandEffect::durable_write(
                "review session --propose",
                vec!["curation_candidates", "audit_log"],
                "Persist session-derived curation candidates",
            ),
            CommandEffect::durable_write(
                "workflow close",
                vec!["memories", "audit_log"],
                "Promote eligible workflow working memories to episodic records",
            ),
            CommandEffect::durable_write(
                "workflow create",
                vec!["memories", "audit_log"],
                "Create workflow working memory and audit provenance",
            ),
            CommandEffect::durable_write(
                "rule add",
                vec![
                    "procedural_rules",
                    "rule_source_memories",
                    "rule_tags",
                    "audit_log",
                    "search_index_jobs",
                ],
                "Store a procedural rule",
            ),
            CommandEffect::durable_write(
                "rule mark",
                vec!["procedural_rules", "audit_log", "search_index_jobs"],
                "Record lifecycle evidence for a procedural rule",
            ),
            CommandEffect::durable_write(
                "rule protect",
                vec!["procedural_rules", "audit_log"],
                "Protect or unprotect a procedural rule",
            ),
            CommandEffect::durable_write(
                "rule update",
                vec![
                    "procedural_rules",
                    "rule_source_memories",
                    "rule_tags",
                    "audit_log",
                    "search_index_jobs",
                ],
                "Update procedural rule metadata",
            ),
            CommandEffect::durable_write(
                "situation adopt",
                vec!["situation_records"],
                "Adopt task text as a persisted situation record via the idempotent fingerprint",
            ),
            CommandEffect::durable_state_write(
                "tripwire check",
                vec!["tripwires", "tripwire_check_events"],
                "tripwire id plus checked_at plus event payload hash",
                "tripwire check event store",
                "Evaluate a persisted tripwire and record the check event unless --dry-run is used",
            ),
            CommandEffect::durable_state_write(
                "maintenance graph-witnesses-prune",
                vec!["graph_algorithm_witnesses"],
                "workspace id plus retention policy plus witness row identity",
                "graph_algorithm_witnesses",
                "Classify graph algorithm witnesses and delete only rows older than policy TTL that are not tied to active snapshots",
            ),
            CommandEffect::schema_migration_run(),
        ]
    }

    fn config_write_commands() -> Vec<CommandEffect> {
        vec![
            CommandEffect::config_write(
                "init",
                vec![".ee/", "ee.toml"],
                "workspace root",
                "Initialize workspace-local ee configuration and storage",
            ),
            CommandEffect::config_write(
                "workspace alias",
                vec![".ee/workspaces.toml"],
                "alias name and workspace root",
                "Create or update a workspace alias",
            ),
            CommandEffect::config_file_write(
                "profile config apply",
                vec![".ee/config.toml"],
                "workspace profile config path plus requested profile",
                "Apply operating profile configuration to the workspace config file",
            ),
            CommandEffect::config_file_write(
                "config set",
                vec![".ee/config.toml"],
                "workspace config path plus exact config key and scalar value",
                "Set a supported workspace configuration key",
            ),
            CommandEffect::harness_hook_settings_write(
                "hook claude-code --install",
                vec![
                    "~/.claude/settings.json",
                    "~/.claude/settings.json.ee-backup",
                ],
                "Claude Code settings path plus generated managed hook snippets",
                "Install ee-managed Claude Code recall and journal hooks into harness settings",
            ),
            CommandEffect::harness_hook_settings_write(
                "hook claude-code --undo",
                vec![
                    "~/.claude/settings.json",
                    "~/.claude/settings.json.ee-backup",
                ],
                "Claude Code settings backup path",
                "Restore Claude Code harness settings from the deterministic ee backup",
            ),
            CommandEffect::harness_hook_settings_write(
                "hook codex --install",
                vec![".codex/hooks.json", ".codex/hooks.json.ee-backup"],
                "Codex hooks path plus generated managed hook snippets",
                "Install ee-managed Codex recall and journal hooks into harness settings",
            ),
            CommandEffect::harness_hook_settings_write(
                "hook codex --undo",
                vec![".codex/hooks.json", ".codex/hooks.json.ee-backup"],
                "Codex hooks backup path",
                "Restore Codex harness settings from the deterministic ee backup",
            ),
            CommandEffect::certificate_key_file_write(
                "certificate keygen",
                vec!["~/.config/ee/keys/<workspace>.ed25519"],
                "workspace key path plus --show/--force mode",
                "Generate or inspect a local certificate signing key",
            ),
            CommandEffect::config_write(
                "mesh disable",
                vec![".ee/config.toml"],
                "workspace id plus mesh disable reason",
                "Disable mesh synchronization for a workspace",
            ),
            CommandEffect::config_write(
                "mesh reenable",
                vec![".ee/config.toml"],
                "workspace id plus mesh reenable reason",
                "Re-enable mesh synchronization for a workspace",
            ),
        ]
    }

    fn workspace_file_write_commands() -> Vec<CommandEffect> {
        vec![
            CommandEffect::shard_fanout_migration(),
            CommandEffect::workspace_file_write(
                "backup create",
                vec![".ee/backups/<backup-id>/"],
                "Create redacted backup artifacts in the workspace",
            ),
            CommandEffect::workspace_file_write(
                "backup restore",
                vec!["<side-path>/"],
                "Restore backup contents into an explicit side path",
            ),
            CommandEffect::workspace_file_write(
                "export",
                vec![".ee/backups/<backup-id>/ or <--output-dir>/<backup-id>/"],
                "Export redacted JSONL records as side-path artifacts",
            ),
            CommandEffect::workspace_file_write(
                "export agentsmd",
                vec!["AGENTS.md (or --file target) managed block plus .ee-backup sibling"],
                "Render the primer rules+warnings sections into the AGENTS.md managed block",
            ),
            CommandEffect::workspace_file_write(
                "artifact relocate",
                vec![
                    "artifact relocation destination paths",
                    "artifact relocation manifest path",
                ],
                "Copy preserved artifacts to explicit relocation destinations without deleting originals",
            ),
            CommandEffect::workspace_state_write(
                "coordination evidence ingest",
                vec![".ee/coordination-fallback-evidence.jsonl"],
                "coordination evidence content hash",
                "Append coordination fallback evidence to the workspace-local evidence log",
            ),
            CommandEffect::workspace_state_write(
                "daemon start",
                vec!["$XDG_RUNTIME_DIR/ee/daemon.sock or ${TMPDIR:-/tmp}/ee-<uid>/daemon.sock"],
                "daemon socket path plus process id",
                "Bind the optional UDS RPC socket outside the workspace",
            ),
            CommandEffect::workspace_state_write(
                "daemon stop",
                vec!["$XDG_RUNTIME_DIR/ee/daemon.sock or ${TMPDIR:-/tmp}/ee-<uid>/daemon.sock"],
                "daemon socket path plus process id",
                "Stop dialing the optional UDS RPC socket and update daemon state",
            ),
            CommandEffect::workspace_file_write(
                "lab capture",
                vec![".ee/lab/episodes"],
                "Writes a frozen episode artifact under .ee/lab/episodes/<EPISODE_ID>/ — task input, policy ids, evidence ids, pack hash, repository fingerprint (N15.3 / bd-17c65.14.15.4)",
            ),
            CommandEffect::workspace_file_write(
                "focus add",
                vec![".ee/focus/state.json"],
                "Add explicit memories to passive focus state without eviction",
            ),
            CommandEffect::workspace_file_write(
                "handoff create",
                vec!["<--out path>"],
                "Write a redacted continuity capsule to a user-specified output path",
            ),
            CommandEffect::workspace_file_write(
                "playbook export",
                vec!["<--out path>"],
                "Write portable procedural rules to a no-overwrite playbook artifact",
            ),
            CommandEffect::workspace_state_write(
                "preflight close",
                vec![".ee/preflight_runs.json"],
                "preflight run id",
                "Close a persisted preflight run in the workspace-local run store",
            ),
            CommandEffect::workspace_state_write(
                "preflight run",
                vec![".ee/preflight_runs.json"],
                "generated preflight run id",
                "Persist an evidence-backed preflight run in the workspace-local run store",
            ),
            CommandEffect::workspace_file_write(
                "support bundle",
                vec!["<--out path>/"],
                "Create a redacted support bundle side-path artifact",
            ),
            CommandEffect::workspace_file_write(
                "team credentials backup",
                vec![".ee/keys/mesh-credential-backup/"],
                "Write an encrypted mesh credential-backup envelope through the hardened keys tree",
            ),
            CommandEffect::workspace_file_write(
                "team credentials restore",
                vec![".ee/keys/mesh/"],
                "Restore pair keys and signing seeds from an encrypted credential-backup envelope",
            ),
            CommandEffect::workspace_file_write(
                "rehearse run",
                vec![
                    "rehearsal artifact root",
                    "tempfile-backed sandbox workspace",
                ],
                "Rehearsal execution writes side-path sandbox artifacts without mutating the source workspace",
            ),
            CommandEffect::workspace_state_write(
                "recorder flight append",
                vec!["flight recorder trace directory"],
                "flight recorder event hash plus sequence",
                "Append an event to a flight-recorder trace",
            ),
            CommandEffect::workspace_state_write(
                "sandbox curate",
                vec![".ee/sandbox/<session>.json"],
                "sandbox session id plus curation event hash",
                "Update sandbox curation state without applying it to durable memories",
            ),
            CommandEffect::workspace_state_write(
                "sandbox import",
                vec![".ee/sandbox/<session>.json"],
                "sandbox session id plus import source hash",
                "Import memories into sandbox state without applying them to durable storage",
            ),
            CommandEffect::workspace_state_write(
                "sandbox remember",
                vec![".ee/sandbox/<session>.json"],
                "sandbox session id plus memory content hash",
                "Record a sandbox memory without applying it to durable storage",
            ),
            CommandEffect::workspace_file_write(
                "focus clear",
                vec![".ee/focus/state.json"],
                "Clear passive focus state by writing an empty state artifact",
            ),
            CommandEffect::workspace_file_write(
                "focus remove",
                vec![".ee/focus/state.json"],
                "Remove explicit memories from passive focus state",
            ),
            CommandEffect::workspace_file_write(
                "focus set",
                vec![".ee/focus/state.json"],
                "Replace passive focus state from explicit command arguments",
            ),
            CommandEffect::workspace_file_write(
                "task-frame create",
                vec![".ee/task_frames.json"],
                "Create a passive task frame without executing commands",
            ),
            CommandEffect::workspace_file_write(
                "task-frame update",
                vec![".ee/task_frames.json"],
                "Update passive task-frame state without executing commands",
            ),
            CommandEffect::workspace_file_write(
                "task-frame close",
                vec![".ee/task_frames.json"],
                "Close a passive task frame without executing commands",
            ),
            CommandEffect::workspace_file_write(
                "task-frame subgoal add",
                vec![".ee/task_frames.json"],
                "Add a passive task-frame subgoal without executing commands",
            ),
        ]
    }

    /// Get the effect entry for a command path.
    #[must_use]
    pub fn get(&self, command_path: &str) -> Option<&CommandEffect> {
        self.entries.get(command_path)
    }

    /// All command paths in the manifest.
    #[must_use]
    pub fn command_paths(&self) -> Vec<&'static str> {
        let mut paths: Vec<_> = self.entries.keys().copied().collect();
        paths.sort_unstable();
        paths
    }

    /// Commands that are safe to call mid-task (read-only).
    #[must_use]
    pub fn safe_mid_task_commands(&self) -> Vec<&CommandEffect> {
        self.entries
            .values()
            .filter(|e| e.is_safe_mid_task())
            .collect()
    }

    /// Commands that perform durable mutations.
    #[must_use]
    pub fn mutating_commands(&self) -> Vec<&CommandEffect> {
        self.entries
            .values()
            .filter(|e| e.default_effect.is_mutating())
            .collect()
    }

    /// Number of commands in the manifest.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// `true` if the manifest is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

impl Default for EffectManifest {
    fn default() -> Self {
        Self::build()
    }
}

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

    type TestResult = Result<(), String>;

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

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

    fn ensure_category<F>(category: &str, entries: Vec<CommandEffect>, accepts: F) -> TestResult
    where
        F: Fn(&CommandEffect) -> bool,
    {
        for entry in entries {
            if !accepts(&entry) {
                return Err(format!(
                    "{} builder contains `{}` with default_effect={} side_effect_class={}",
                    category,
                    entry.command_path,
                    entry.default_effect.as_str(),
                    entry.mutation_contract.side_effect_class.as_str()
                ));
            }
        }
        Ok(())
    }

    #[test]
    fn effect_class_strings_are_stable() -> TestResult {
        ensure(EffectClass::ReadOnly.as_str(), "read_only", "read_only")?;
        ensure(
            EffectClass::DerivedArtifactWrite.as_str(),
            "derived_artifact_write",
            "derived_artifact_write",
        )?;
        ensure(
            EffectClass::DurableMemoryWrite.as_str(),
            "durable_memory_write",
            "durable_memory_write",
        )?;
        ensure(
            EffectClass::WorkspaceFileWrite.as_str(),
            "workspace_file_write",
            "workspace_file_write",
        )
    }

    #[test]
    fn side_effect_class_strings_match_matrix_vocabulary() -> TestResult {
        ensure(
            SideEffectClass::ReadOnly.as_str(),
            "class=read_only",
            "read_only",
        )?;
        ensure(
            SideEffectClass::AppendOnly.as_str(),
            "class=append_only",
            "append_only",
        )?;
        ensure(
            SideEffectClass::ReadOnlyNow.as_str(),
            "class=read_only_now",
            "read_only_now",
        )?;
        ensure(
            SideEffectClass::ReportOnly.as_str(),
            "class=report_only",
            "report_only",
        )?;
        ensure(
            SideEffectClass::ReadOnlyOrUnavailable.as_str(),
            "class=read_only_or_unavailable",
            "read_only_or_unavailable",
        )?;
        ensure(
            SideEffectClass::AuditedMutation.as_str(),
            "class=audited_mutation",
            "audited_mutation",
        )?;
        ensure(
            SideEffectClass::DerivedAssetRebuild.as_str(),
            "class=derived_asset_rebuild",
            "derived_asset_rebuild",
        )?;
        ensure(
            SideEffectClass::SidePathArtifact.as_str(),
            "class=side_path_artifact",
            "side_path_artifact",
        )?;
        ensure(
            SideEffectClass::SupervisedJobs.as_str(),
            "class=supervised_jobs",
            "supervised_jobs",
        )?;
        ensure(SideEffectClass::Mixed.as_str(), "class=mixed", "mixed")?;
        ensure(
            SideEffectClass::DegradedUnavailable.as_str(),
            "class=degraded_unavailable",
            "degraded_unavailable",
        )?;
        ensure(
            SideEffectClass::ReportOnlyOrAppend.as_str(),
            "class=report_only_or_append",
            "report_only_or_append",
        )?;
        ensure(
            SideEffectClass::ReportOnlyOrAuditedMutation.as_str(),
            "class=report_only_or_audited_mutation",
            "report_only_or_audited_mutation",
        )
    }

    #[test]
    fn effect_class_is_mutating_classifies_correctly() -> TestResult {
        ensure(EffectClass::ReadOnly.is_mutating(), false, "read_only")?;
        ensure(
            EffectClass::DerivedArtifactWrite.is_mutating(),
            true,
            "derived_artifact_write",
        )?;
        ensure(
            EffectClass::DurableMemoryWrite.is_mutating(),
            true,
            "durable_memory_write",
        )?;
        ensure(
            EffectClass::WorkspaceFileWrite.is_mutating(),
            true,
            "workspace_file_write",
        )
    }

    #[test]
    fn idempotency_strings_are_stable() -> TestResult {
        ensure(
            IdempotencyClass::Idempotent.as_str(),
            "idempotent",
            "idempotent",
        )?;
        ensure(
            IdempotencyClass::NonIdempotent.as_str(),
            "non_idempotent",
            "non_idempotent",
        )?;
        ensure(
            IdempotencyClass::DryRunAvailable.as_str(),
            "dry_run_available",
            "dry_run_available",
        )
    }

    #[test]
    fn runtime_class_strings_are_stable() -> TestResult {
        ensure(RuntimeClass::Immediate.as_str(), "immediate", "immediate")?;
        ensure(RuntimeClass::Bounded.as_str(), "bounded", "bounded")?;
        ensure(
            RuntimeClass::LongRunning.as_str(),
            "long_running",
            "long_running",
        )?;
        ensure(
            RuntimeClass::MultiStage.as_str(),
            "multi_stage",
            "multi_stage",
        )?;
        ensure(
            RuntimeClass::Supervised.as_str(),
            "supervised",
            "supervised",
        )
    }

    #[test]
    fn runtime_budget_math_is_deterministic() -> TestResult {
        let long = CommandRuntimeContract::long_running_derived();
        ensure(
            long.requires_budget(),
            true,
            "long-running work requires budget",
        )?;
        ensure(
            long.effective_budget_ms(None),
            Ok(Some(300_000)),
            "default long-running budget",
        )?;
        ensure(
            long.effective_budget_ms(Some(42)),
            Ok(Some(42)),
            "explicit budget overrides default",
        )?;
        ensure(
            long.effective_budget_ms(Some(0)),
            Err("runtime budget must be greater than zero"),
            "zero budget rejected",
        )?;

        let immediate = CommandRuntimeContract::immediate();
        ensure(
            immediate.requires_budget(),
            false,
            "immediate work does not require budget",
        )?;
        ensure(
            immediate.effective_budget_ms(None),
            Ok(None),
            "immediate work is unbounded by default",
        )
    }

    #[test]
    fn command_effect_read_only_is_safe_mid_task() -> TestResult {
        let effect = CommandEffect::read_only("status", "Report status");
        ensure(
            effect.is_safe_mid_task(),
            true,
            "read_only is safe mid-task",
        )?;
        ensure(
            effect.default_effect,
            EffectClass::ReadOnly,
            "default effect",
        )?;
        ensure(
            effect.runtime_contract.runtime_class,
            RuntimeClass::Bounded,
            "read-only work is bounded",
        )?;
        ensure(effect.requires_audit, false, "no audit required")
    }

    #[test]
    fn command_effect_durable_write_requires_audit() -> TestResult {
        let effect = CommandEffect::durable_write("remember", vec!["memories"], "Store memory");
        ensure(
            effect.is_safe_mid_task(),
            false,
            "durable write not safe mid-task",
        )?;
        ensure(
            effect.default_effect,
            EffectClass::DurableMemoryWrite,
            "default effect",
        )?;
        ensure(effect.requires_audit, true, "audit required")?;
        ensure(
            effect.dry_run_effect,
            Some(EffectClass::ReadOnly),
            "dry_run reduces to read_only",
        )?;
        ensure(
            effect.mutation_contract.side_effect_class,
            SideEffectClass::AuditedMutation,
            "durable write has audited contract",
        )?;
        ensure(
            effect.mutation_contract.audit_surface,
            Some("audit_log"),
            "durable write names audit surface",
        )?;
        ensure(
            effect.runtime_contract.runtime_class,
            RuntimeClass::MultiStage,
            "durable write has multi-stage runtime",
        )
    }

    #[test]
    fn command_effect_append_only_write_uses_idempotency_key() -> TestResult {
        let effect = CommandEffect::append_only_write(
            "artifact register",
            vec!["artifacts", "audit_log"],
            "content hash",
            "Register artifact",
        );
        ensure(
            effect.default_effect,
            EffectClass::DurableMemoryWrite,
            "append-only writes durable records",
        )?;
        ensure(
            effect.idempotency,
            IdempotencyClass::Idempotent,
            "append-only retries are idempotent",
        )?;
        ensure(
            effect.mutation_contract.side_effect_class,
            SideEffectClass::AppendOnly,
            "append-only class",
        )?;
        ensure(
            effect.mutation_contract.idempotency_key,
            Some("content hash"),
            "idempotency key",
        )?;
        ensure(
            effect.runtime_contract.runtime_class,
            RuntimeClass::MultiStage,
            "append-only write has multi-stage runtime",
        )?;
        ensure(effect.requires_audit, true, "append-only requires audit")
    }

    #[test]
    fn command_effect_degraded_unavailable_is_read_only_with_code() -> TestResult {
        let effect = CommandEffect::degraded_unavailable(
            "lab replay",
            "lab_replay_unavailable",
            "Lab replay abstains until replay evidence exists",
        );
        ensure(
            effect.default_effect,
            EffectClass::ReadOnly,
            "degraded unavailable is read-only",
        )?;
        ensure(
            effect.mutation_contract.side_effect_class,
            SideEffectClass::DegradedUnavailable,
            "degraded side-effect class",
        )?;
        ensure(
            effect.write_surfaces.is_empty(),
            true,
            "degraded command has no write surfaces",
        )?;
        ensure(
            effect.mutation_contract.degraded_code,
            Some("lab_replay_unavailable"),
            "degraded code is explicit",
        )?;
        ensure(
            effect.runtime_contract.runtime_class,
            RuntimeClass::Immediate,
            "degraded unavailable returns immediately",
        )?;
        ensure(
            effect.requires_audit,
            false,
            "degraded command does not audit",
        )
    }

    #[test]
    fn command_effect_workspace_file_write_uses_side_path_no_delete_contract() -> TestResult {
        let effect = CommandEffect::workspace_file_write(
            "backup restore",
            vec!["<side-path>/"],
            "Restore backup into an explicit side path",
        );

        ensure(
            effect.default_effect,
            EffectClass::WorkspaceFileWrite,
            "workspace write effect",
        )?;
        ensure(
            effect.dry_run_effect,
            Some(EffectClass::ReadOnly),
            "dry-run is read-only",
        )?;
        ensure(
            effect.mutation_contract.side_effect_class,
            SideEffectClass::SidePathArtifact,
            "workspace writes are side-path artifacts",
        )?;
        ensure(
            effect.requires_audit,
            true,
            "side-path artifacts require manifest audit",
        )?;
        ensure(
            effect.runtime_contract.runtime_class,
            RuntimeClass::MultiStage,
            "side-path artifacts are multi-stage",
        )?;
        ensure(
            effect
                .mutation_contract
                .no_overwrite_behavior
                .is_some_and(|policy| {
                    policy.contains("no-overwrite") && policy.contains("no-delete")
                }),
            true,
            "side-path policy names no-overwrite and no-delete",
        )?;
        ensure(
            effect
                .mutation_contract
                .recovery_behavior
                .contains("never deleted by ee"),
            true,
            "side-path recovery never deletes partial output",
        )
    }

    #[test]
    fn command_effect_derived_write_is_idempotent() -> TestResult {
        let effect =
            CommandEffect::derived_write("index rebuild", vec![".ee/index/"], "Rebuild indexes");
        ensure(
            effect.idempotency,
            IdempotencyClass::Idempotent,
            "derived write is idempotent",
        )?;
        ensure(
            effect.default_effect,
            EffectClass::DerivedArtifactWrite,
            "default effect",
        )?;
        ensure(
            effect.mutation_contract.side_effect_class,
            SideEffectClass::DerivedAssetRebuild,
            "derived write uses derived rebuild contract",
        )?;
        ensure(
            effect.mutation_contract.declares_no_source_mutation(),
            true,
            "derived write leaves source DB unchanged",
        )?;
        ensure(
            effect.runtime_contract.runtime_class,
            RuntimeClass::LongRunning,
            "derived writes are long-running",
        )
    }

    #[test]
    fn manifest_build_includes_all_command_classes() -> TestResult {
        let manifest = EffectManifest::build();

        ensure_at_least(manifest.len(), 20, "at least 20 commands")?;

        let safe = manifest.safe_mid_task_commands();
        ensure_at_least(safe.len(), 15, "at least 15 safe commands")?;

        let mutating = manifest.mutating_commands();
        ensure_at_least(mutating.len(), 2, "at least 2 mutating commands")
    }

    #[test]
    fn manifest_build_has_no_duplicate_command_paths() -> TestResult {
        // Pin the no-duplicate invariant directly via the category-
        // vector unions rather than only via `build()` (which already
        // panics on duplicate via `insert_unique`). The vector unions
        // exhibit the same drift surface but with a clearer test-
        // failure message identifying the offending category pair —
        // and the test also fails cleanly in release builds (where
        // `debug_assert!` would be a no-op).
        use std::collections::HashMap;
        let mut origins: HashMap<&'static str, &'static str> = HashMap::new();
        let category_vectors: &[(&'static str, Vec<CommandEffect>)] = &[
            ("read_only", EffectManifest::read_only_commands()),
            (
                "degraded_unavailable",
                EffectManifest::degraded_unavailable_commands(),
            ),
            ("derived_write", EffectManifest::derived_write_commands()),
            (
                "external_io_write",
                EffectManifest::external_io_write_commands(),
            ),
            ("supervised_job", EffectManifest::supervised_job_commands()),
            (
                "append_only_write",
                EffectManifest::append_only_write_commands(),
            ),
            ("durable_write", EffectManifest::durable_write_commands()),
            ("config_write", EffectManifest::config_write_commands()),
            (
                "workspace_file_write",
                EffectManifest::workspace_file_write_commands(),
            ),
        ];
        for (category, entries) in category_vectors {
            // Iterating `&[(K, Vec<V>)]` makes `category: &&'static str`
            // and `entries: &Vec<CommandEffect>`; dereference `category`
            // so the HashMap value type matches and the error message
            // shows the bare category name, not a `&str` debug form.
            let category = *category;
            for entry in entries {
                if let Some(previous_category) = origins.insert(entry.command_path, category) {
                    return Err(format!(
                        "command path `{}` is declared in both `{previous_category}` and `{category}` categories; a command must appear in exactly one",
                        entry.command_path
                    ));
                }
            }
        }
        Ok(())
    }

    #[test]
    fn manifest_category_builders_match_declared_effect_classes() -> TestResult {
        ensure_category("read_only", EffectManifest::read_only_commands(), |entry| {
            entry.default_effect == EffectClass::ReadOnly
                && entry.mutation_contract.side_effect_class != SideEffectClass::DegradedUnavailable
        })?;
        ensure_category(
            "degraded_unavailable",
            EffectManifest::degraded_unavailable_commands(),
            |entry| {
                entry.default_effect == EffectClass::ReadOnly
                    && entry.mutation_contract.side_effect_class
                        == SideEffectClass::DegradedUnavailable
                    && entry.write_surfaces.is_empty()
                    && !entry.requires_audit
                    && entry.mutation_contract.degraded_code.is_some()
            },
        )?;
        ensure_category(
            "derived_write",
            EffectManifest::derived_write_commands(),
            |entry| entry.default_effect == EffectClass::DerivedArtifactWrite,
        )?;
        ensure_category(
            "external_io_write",
            EffectManifest::external_io_write_commands(),
            |entry| entry.default_effect == EffectClass::ExternalIo,
        )?;
        ensure_category(
            "supervised_job",
            EffectManifest::supervised_job_commands(),
            |entry| entry.mutation_contract.side_effect_class == SideEffectClass::SupervisedJobs,
        )?;
        ensure_category(
            "append_only_write",
            EffectManifest::append_only_write_commands(),
            |entry| entry.mutation_contract.side_effect_class == SideEffectClass::AppendOnly,
        )?;
        ensure_category(
            "durable_write",
            EffectManifest::durable_write_commands(),
            |entry| {
                entry.default_effect == EffectClass::DurableMemoryWrite
                    && entry.mutation_contract.side_effect_class == SideEffectClass::AuditedMutation
            },
        )?;
        ensure_category(
            "config_write",
            EffectManifest::config_write_commands(),
            |entry| entry.default_effect == EffectClass::ConfigWrite,
        )?;
        ensure_category(
            "workspace_file_write",
            EffectManifest::workspace_file_write_commands(),
            |entry| entry.default_effect == EffectClass::WorkspaceFileWrite,
        )
    }

    #[test]
    fn manifest_get_returns_correct_entry() -> TestResult {
        let manifest = EffectManifest::build();

        let recipe = manifest
            .get("plan recipe save")
            .ok_or("recipe save effect missing")?;
        ensure(
            recipe.default_effect,
            EffectClass::DurableMemoryWrite,
            "recipe save writes durable state",
        )?;
        ensure(
            recipe.dry_run_effect,
            Some(EffectClass::ReadOnly),
            "recipe preview is read-only",
        )?;
        ensure(recipe.requires_audit, true, "recipe save requires an audit")?;
        ensure(
            recipe.write_surfaces.db_tables.clone(),
            vec!["plan_recipes", "audit_log"],
            "recipe mutation surfaces",
        )?;

        let status = manifest.get("status");
        ensure(status.is_some(), true, "status exists")?;
        ensure(
            status.map(|e| e.default_effect),
            Some(EffectClass::ReadOnly),
            "status is read_only",
        )?;

        let remember = manifest.get("remember");
        ensure(remember.is_some(), true, "remember exists")?;
        ensure(
            remember.map(|e| e.default_effect),
            Some(EffectClass::DurableMemoryWrite),
            "remember is durable_memory_write",
        )?;

        let outcome = manifest.get("outcome");
        ensure(outcome.is_some(), true, "outcome exists")?;
        ensure(
            outcome.map(|e| e.write_surfaces.db_tables.clone()),
            Some(vec!["feedback_events", "audit_log"]),
            "outcome writes feedback and audit",
        )?;

        let preflight_check = manifest
            .get("preflight check")
            .ok_or_else(|| "preflight check not found".to_owned())?;
        let preflight_guard = manifest
            .get("preflight guard")
            .ok_or_else(|| "preflight guard alias not found".to_owned())?;
        ensure(
            preflight_guard.default_effect,
            preflight_check.default_effect,
            "preflight guard alias matches preflight check effect",
        )?;
        ensure(
            preflight_guard.mutation_contract.side_effect_class,
            preflight_check.mutation_contract.side_effect_class,
            "preflight guard alias matches preflight check mutation class",
        )?;
        ensure(
            preflight_guard.requires_audit,
            false,
            "preflight guard alias is read-only and needs no audit",
        )?;
        ensure(
            preflight_guard.write_surfaces.is_empty(),
            true,
            "preflight guard alias declares no write surfaces",
        )?;

        let backup = manifest.get("backup create");
        ensure(backup.is_some(), true, "backup create exists")?;
        ensure(
            backup.map(|e| e.default_effect),
            Some(EffectClass::WorkspaceFileWrite),
            "backup create writes workspace files",
        )?;

        let decay_sweep = manifest.get("daemon foreground decay_sweep");
        ensure(
            decay_sweep.is_some(),
            true,
            "daemon foreground decay_sweep exists",
        )?;
        ensure(
            decay_sweep.map(|e| e.mutation_contract.side_effect_class),
            Some(SideEffectClass::SupervisedJobs),
            "daemon decay sweep uses supervised job contract",
        )?;
        ensure(
            decay_sweep.map(|e| e.runtime_contract.runtime_class),
            Some(RuntimeClass::Supervised),
            "daemon decay sweep runtime",
        )
    }

    #[test]
    fn manifest_classifies_migrate_command_paths() -> TestResult {
        let manifest = EffectManifest::build();

        let status = manifest
            .get("migrate status")
            .ok_or_else(|| "migrate status not found".to_owned())?;
        ensure(
            status.default_effect,
            EffectClass::ReadOnly,
            "migrate status is read-only",
        )?;
        ensure(
            status.read_snapshot(),
            true,
            "migrate status reads through a DB snapshot",
        )?;

        let run = manifest
            .get("migrate run")
            .ok_or_else(|| "migrate run not found".to_owned())?;
        ensure(
            run.default_effect,
            EffectClass::DurableMemoryWrite,
            "migrate run writes durable schema state",
        )?;
        ensure(
            run.dry_run_effect,
            Some(EffectClass::ReadOnly),
            "migrate run dry-run is read-only",
        )?;
        ensure(
            run.mutation_contract.side_effect_class,
            SideEffectClass::AuditedMutation,
            "migrate run has audited mutation contract",
        )?;
        ensure(
            run.write_surfaces
                .db_tables
                .contains(&"ee_schema_migrations"),
            true,
            "migrate run names schema migration table",
        )?;
        ensure(
            run.write_surfaces.derived_paths.contains(&".ee/index/"),
            true,
            "migrate run names post-migration index rebuild",
        )?;

        let shard = manifest
            .get("migrate shard-fanout")
            .ok_or_else(|| "migrate shard-fanout not found".to_owned())?;
        ensure(
            shard.default_effect,
            EffectClass::WorkspaceFileWrite,
            "migrate shard-fanout writes shard files",
        )?;
        ensure(
            shard.dry_run_effect,
            Some(EffectClass::ReadOnly),
            "migrate shard-fanout dry-run is read-only",
        )?;
        ensure(
            shard.mutation_contract.side_effect_class,
            SideEffectClass::AuditedMutation,
            "migrate shard-fanout has audited mutation contract",
        )?;
        ensure(
            shard
                .write_surfaces
                .workspace_files
                .contains(&"<shards-dir>/catalog.db"),
            true,
            "migrate shard-fanout names shard catalog file",
        )
    }

    #[test]
    fn manifest_distinguishes_append_only_imports_from_audited_mutations() -> TestResult {
        let manifest = EffectManifest::build();

        for command in [
            "artifact register",
            "import cass",
            "import jsonl",
            "import eidetic-legacy",
        ] {
            let effect = manifest
                .get(command)
                .ok_or_else(|| format!("{command} not found"))?;
            ensure(
                effect.mutation_contract.side_effect_class,
                SideEffectClass::AppendOnly,
                &format!("{command} is append-only"),
            )?;
            ensure(
                effect.idempotency,
                IdempotencyClass::Idempotent,
                &format!("{command} retries by idempotency key"),
            )?;
        }

        let remember = manifest
            .get("remember")
            .ok_or_else(|| "remember not found".to_owned())?;
        ensure(
            remember.mutation_contract.side_effect_class,
            SideEffectClass::AuditedMutation,
            "remember remains an audited mutation",
        )
    }

    #[test]
    fn manifest_tracks_lab_replay_as_available_read_only_path() -> TestResult {
        let manifest = EffectManifest::build();

        let command = "lab replay";
        let effect = manifest
            .get(command)
            .ok_or_else(|| format!("{command} not found"))?;
        ensure(
            effect.default_effect,
            EffectClass::ReadOnly,
            &format!("{command} is read-only"),
        )?;
        ensure(
            effect.mutation_contract.side_effect_class,
            SideEffectClass::ReadOnly,
            &format!("{command} uses read-only class"),
        )?;
        ensure(
            effect.write_surfaces.is_empty(),
            true,
            &format!("{command} has no write surfaces"),
        )?;
        ensure(
            effect.mutation_contract.degraded_code,
            None,
            &format!("{command} has no unavailable degraded code"),
        )?;

        Ok(())
    }

    #[test]
    fn manifest_classifies_mesh_lane_mutations_as_audited_durable_writes() -> TestResult {
        let manifest = EffectManifest::build();
        for command in ["mesh grant", "mesh revoke-lane"] {
            let effect = manifest
                .get(command)
                .ok_or_else(|| format!("{command} not found"))?;
            ensure(
                effect.default_effect,
                EffectClass::DurableMemoryWrite,
                &format!("{command} is a durable write"),
            )?;
            ensure(
                effect.requires_audit,
                true,
                &format!("{command} requires audit"),
            )?;
            ensure(
                effect.write_surfaces.db_tables.clone(),
                vec!["mesh_lane_grant_states", "audit_log"],
                &format!("{command} declares exact write surfaces"),
            )?;
        }
        Ok(())
    }

    #[test]
    fn manifest_tracks_demo_run_as_audited_external_io() -> TestResult {
        let manifest = EffectManifest::build();
        let effect = manifest
            .get("demo run")
            .ok_or_else(|| "demo run not found".to_owned())?;

        ensure(
            effect.default_effect,
            EffectClass::ExternalIo,
            "demo run executes manifest commands",
        )?;
        ensure(
            effect.dry_run_effect,
            Some(EffectClass::ReadOnly),
            "demo run --dry-run is read-only",
        )?;
        ensure(
            effect.mutation_contract.side_effect_class,
            SideEffectClass::AuditedMutation,
            "demo run writes audit rows",
        )?;
        ensure(
            effect.write_surfaces.db_tables.contains(&"audit_log"),
            true,
            "demo run writes audit_log",
        )?;
        ensure(
            effect.write_surfaces.workspace_files.is_empty(),
            false,
            "demo run names evidence/artifact write surfaces",
        )?;
        ensure(
            effect.mutation_contract.degraded_code,
            None,
            "demo run has no unavailable sentinel",
        )
    }

    #[test]
    fn manifest_command_paths_are_sorted() -> TestResult {
        let manifest = EffectManifest::build();
        let paths = manifest.command_paths();

        let mut sorted = paths.clone();
        sorted.sort_unstable();
        ensure(paths, sorted, "paths are sorted")
    }

    #[test]
    fn write_surfaces_none_is_empty() -> TestResult {
        let surfaces = WriteSurfaces::none();
        ensure(surfaces.is_empty(), true, "none is empty")
    }

    #[test]
    fn remember_command_writes_to_memory_tables() -> TestResult {
        let manifest = EffectManifest::build();
        let remember = manifest
            .get("remember")
            .ok_or_else(|| "remember not found".to_string())?;

        let has_memories = remember.write_surfaces.db_tables.contains(&"memories");
        ensure(has_memories, true, "writes to memories table")?;

        let has_audit = remember.write_surfaces.db_tables.contains(&"audit_log");
        ensure(has_audit, true, "writes to audit_log")
    }

    #[test]
    fn index_rebuild_writes_to_index_path() -> TestResult {
        let manifest = EffectManifest::build();
        let rebuild = manifest
            .get("index rebuild")
            .ok_or_else(|| "index rebuild not found".to_string())?;

        let has_index = rebuild.write_surfaces.derived_paths.contains(&".ee/index/");
        ensure(has_index, true, "writes to .ee/index/")
    }

    // ========================================================================
    // No-Mutation Contract Tests
    // ========================================================================

    #[test]
    fn all_read_only_commands_have_empty_write_surfaces() -> TestResult {
        let manifest = EffectManifest::build();

        for effect in manifest.safe_mid_task_commands() {
            if !effect.write_surfaces.is_empty() {
                return Err(format!(
                    "Read-only command '{}' has non-empty write surfaces",
                    effect.command_path
                ));
            }
        }
        Ok(())
    }

    #[test]
    fn db_backed_read_only_commands_declare_read_snapshot_requirement() -> TestResult {
        let manifest = EffectManifest::build();
        let db_backed = [
            "context",
            "orient",
            "search",
            "why",
            "status",
            "doctor",
            "memory drift",
            "memory list",
            "memory show",
            "pack replay",
            "graph pagerank",
            "db status",
            "audit timeline",
            "curate candidates",
            "diag provenance",
            "trust report",
            "swarm brief",
        ];

        for command in db_backed {
            let effect = manifest
                .get(command)
                .ok_or_else(|| format!("{command} not found"))?;
            ensure(
                effect.default_effect,
                EffectClass::ReadOnly,
                &format!("{command} remains read-only"),
            )?;
            ensure(
                effect.read_snapshot(),
                true,
                &format!("{command} declares read snapshot requirement"),
            )?;
        }

        for command in ["help", "version", "completion"] {
            let effect = manifest
                .get(command)
                .ok_or_else(|| format!("{command} not found"))?;
            ensure(
                effect.read_snapshot(),
                false,
                &format!("{command} does not require a DB read snapshot"),
            )?;
        }

        Ok(())
    }

    #[test]
    fn all_read_only_commands_do_not_require_audit() -> TestResult {
        let manifest = EffectManifest::build();

        for effect in manifest.safe_mid_task_commands() {
            if effect.requires_audit {
                return Err(format!(
                    "Read-only command '{}' requires audit, but should not",
                    effect.command_path
                ));
            }
        }
        Ok(())
    }

    #[test]
    fn all_durable_write_commands_require_audit() -> TestResult {
        let manifest = EffectManifest::build();

        for effect in manifest.entries.values() {
            if effect.default_effect == EffectClass::DurableMemoryWrite && !effect.requires_audit {
                return Err(format!(
                    "Durable-write command '{}' does not require audit, but should",
                    effect.command_path
                ));
            }
        }
        Ok(())
    }

    #[test]
    fn all_mutating_commands_have_s43e_contract_metadata() -> TestResult {
        let manifest = EffectManifest::build();

        for effect in manifest.mutating_commands() {
            let contract = &effect.mutation_contract;
            if contract.transaction_scope.is_none() {
                return Err(format!(
                    "Mutating command '{}' has no transaction scope",
                    effect.command_path
                ));
            }
            if contract.idempotency_key.is_none() {
                return Err(format!(
                    "Mutating command '{}' has no idempotency key",
                    effect.command_path
                ));
            }
            if contract.dry_run_behavior.is_none() {
                return Err(format!(
                    "Mutating command '{}' has no dry-run behavior",
                    effect.command_path
                ));
            }
            if contract.recovery_behavior.is_empty()
                || contract.db_generation_effect.is_empty()
                || contract.index_generation_effect.is_empty()
            {
                return Err(format!(
                    "Mutating command '{}' has incomplete recovery/generation effects",
                    effect.command_path
                ));
            }
        }
        Ok(())
    }

    #[test]
    fn side_path_artifact_commands_name_no_overwrite_behavior() -> TestResult {
        let manifest = EffectManifest::build();

        for effect in manifest.mutating_commands() {
            let contract = &effect.mutation_contract;
            if contract.side_effect_class.requires_no_overwrite_contract() {
                let Some(policy) = contract.no_overwrite_behavior else {
                    return Err(format!(
                        "Side-path command '{}' has no no-overwrite behavior",
                        effect.command_path
                    ));
                };
                if !policy.contains("no-overwrite") || !policy.contains("no-delete") {
                    return Err(format!(
                        "Side-path command '{}' must name no-overwrite and no-delete behavior",
                        effect.command_path
                    ));
                }
                if !contract.recovery_behavior.contains("never deleted by ee") {
                    return Err(format!(
                        "Side-path command '{}' must never delete partial output during recovery",
                        effect.command_path
                    ));
                }
            }
        }
        Ok(())
    }

    #[test]
    fn all_mutating_commands_have_dry_run_option() -> TestResult {
        let manifest = EffectManifest::build();

        for effect in manifest.mutating_commands() {
            if effect.dry_run_effect.is_none() {
                return Err(format!(
                    "Mutating command '{}' has no dry_run option",
                    effect.command_path
                ));
            }
        }
        Ok(())
    }

    #[test]
    fn effect_class_ordering_is_monotone() -> TestResult {
        // ReadOnly < DerivedArtifactWrite < DurableMemoryWrite < ...
        ensure(
            EffectClass::ReadOnly < EffectClass::DerivedArtifactWrite,
            true,
            "read_only < derived_artifact_write",
        )?;
        ensure(
            EffectClass::DerivedArtifactWrite < EffectClass::DurableMemoryWrite,
            true,
            "derived_artifact_write < durable_memory_write",
        )?;
        ensure(
            EffectClass::DurableMemoryWrite < EffectClass::WorkspaceFileWrite,
            true,
            "durable_memory_write < workspace_file_write",
        )
    }
}