khive-runtime 0.11.0

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
//! Verb response presentation modes and transformation.
//!
//! Transforms canonical handler output into caller-appropriate form after dispatch
//! and before wire serialization. `Agent` mode abbreviates UUIDs and drops
//! empty fields; `Verbose` and `Human` pass through canonical JSON unchanged.
//!
//! This module also contains the `OutputFormat` axis (ADR-078) which governs how
//! the resulting `serde_json::Value` is serialized or rendered to an output string.
//! `PresentationMode` and `OutputFormat` compose independently.

use std::{cmp::Ordering, collections::HashSet};

use khive_types::VerbPresentationPolicy;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

/// Exact note-body locations selected by the request boundary for
/// `get/list(parse_content=true)`. No policy marker is inferred from user JSON.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NoteContentScope {
    #[default]
    None,
    Record,
    Items,
    Notes,
}

impl NoteContentScope {
    /// Keep note bodies outside a metadata-only transform, including nulls,
    /// empty containers/strings, and fields that resemble IDs or timestamps.
    /// The transform must preserve record order and the get/list envelope.
    pub fn protect(self, mut value: Value, transform: impl FnOnce(Value) -> Value) -> Value {
        if self == Self::None {
            return transform(value);
        }
        fn take_content(record: &mut Value) -> Option<Value> {
            record.as_object_mut()?.remove("content")
        }
        fn restore_content(record: &mut Value, content: Option<Value>) {
            if let (Some(record), Some(content)) = (record.as_object_mut(), content) {
                record.insert("content".to_string(), content);
            }
        }
        if self == Self::Record {
            let content = take_content(&mut value);
            let mut value = transform(value);
            restore_content(&mut value, content);
            return value;
        }
        let key = if self == Self::Items {
            "items"
        } else {
            "notes"
        };
        let contents: Vec<_> = value
            .get_mut(key)
            .and_then(Value::as_array_mut)
            .into_iter()
            .flatten()
            .map(take_content)
            .collect();
        let mut value = transform(value);
        if let Some(records) = value.get_mut(key).and_then(Value::as_array_mut) {
            for (record, content) in records.iter_mut().zip(contents) {
                restore_content(record, content);
            }
        }
        value
    }

    fn stringify_table_content(self, value: &mut Value) {
        fn stringify(record: &mut Value) {
            if let Some(content) = record.get_mut("content") {
                if content.is_object() || content.is_array() {
                    *content = Value::String(content.to_string());
                }
            }
        }
        match self {
            Self::None => {}
            Self::Record => stringify(value),
            Self::Items | Self::Notes => {
                let key = if self == Self::Items {
                    "items"
                } else {
                    "notes"
                };
                if let Some(records) = value.get_mut(key).and_then(Value::as_array_mut) {
                    records.iter_mut().for_each(stringify);
                }
            }
        }
    }
}

// ── OutputFormat ─────────────────────────────────────────────────────────────

/// Output serialization format for verb results (ADR-078).
///
/// Orthogonal to [`PresentationMode`]: `PresentationMode` controls field-level
/// transforms (UUID shortening, exact UTC timestamps, empty-field dropping);
/// `OutputFormat` controls how the resulting `serde_json::Value` is serialized
/// or rendered to the wire string.
///
/// Default is [`OutputFormat::Json`] on every surface: compact and
/// machine-walkable. Verbose JSON is lossless; Agent JSON additionally elides
/// `namespace="local"` and duplicate `properties` entries (ADR-078 Amendment
/// 3, Machine scope) but keeps `full_id` — it is the caller's chaining
/// handle, not a redundant field.
///
/// Note: `Yaml` is a clean follow-up — implemented as a 3-variant enum
/// (`Json`, `Auto`, `Table`) per ADR-078 §"yaml" which permits omission when
/// the in-tree emitter would balloon.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum OutputFormat {
    /// Compact JSON (`serde_json::to_string`). Default; lossless in Verbose
    /// presentation, Machine-scope redundancy-reduced in Agent presentation
    /// (`full_id` retained — see [`RedundancyScope`]).
    #[default]
    Json,
    /// Shape-aware: markdown table for homogeneous record arrays (with
    /// envelope siblings preserved as trailing `key: value` lines),
    /// compact-JSON fallback for every other shape.
    Auto,
    /// Force the markdown-table renderer regardless of detected shape.
    /// Ordinary results share Auto's dispatch. Opt-in parsed note bodies are
    /// stringified for table display; Auto preserves their JSON values.
    Table,
}

/// Cell truncation limit for markdown-table rendering (ADR-078 §3a).
const CELL_TRUNCATE: usize = 120;

/// Scalar payload fields hoisted from `properties` to the top level in the
/// auto/table pre-pass, when no top-level sibling of that name exists.
/// View-only (never applied to `json`): without the hoist, a table row for a
/// scheduled event cannot say when it fires or whether it is pending —
/// those fields exist only inside the nested `properties` bag.
const PROPERTY_HOIST_FIELDS: &[&str] = &["trigger_at", "due", "status"];

// ── Public render entry point ────────────────────────────────────────────────

/// Render a successful verb result value to a wire string using the given format.
///
/// Called at the single serialization seam (ADR-078 §9) AFTER all `$prev` chain
/// resolution and AFTER the [`PresentationMode`] transform.
///
/// Error envelopes (`ok=false`) are never passed here — the caller must handle
/// them as compact JSON directly (ADR-078 §8.2).
///
/// Agent presentation applies the redundancy-reduction pre-pass (§7) for every
/// format, including JSON — at Machine scope for `json` (keeps `full_id`) and
/// View scope for `auto`/`table` (drops it too, ADR-078 Amendment 3). Auto/table
/// also apply View scope for Human presentation; Verbose remains canonical and
/// unreduced. The prepared value is then encoded as compact JSON or dispatched
/// to the shape-aware renderer. Verbose also disables cell truncation in the
/// table renderer (§3a).
pub fn render_format(value: Value, format: OutputFormat, presentation: PresentationMode) -> String {
    render_format_with_note_content(value, format, presentation, NoteContentScope::None)
}

/// Render an opt-in parsed-note response without treating its body as metadata
/// or a top-level record table. Auto preserves parsed values; Table stringifies
/// non-scalar content for display only.
pub fn render_format_with_note_content(
    value: Value,
    format: OutputFormat,
    presentation: PresentationMode,
    content_scope: NoteContentScope,
) -> String {
    let value = prepare_format_value_with_note_content(value, format, presentation, content_scope);
    match format {
        OutputFormat::Json => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
        OutputFormat::Auto if content_scope != NoteContentScope::None => {
            serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string())
        }
        OutputFormat::Auto | OutputFormat::Table => {
            render_auto(value, presentation != PresentationMode::Verbose)
        }
    }
}

/// Prepare a successful result for its requested format at the wire boundary.
///
/// JSON remains a JSON value in compounded response envelopes, so the MCP seam
/// uses this helper directly instead of round-tripping through a serialized
/// string. Keeping the policy here prevents the single-value and compounded
/// paths from drifting.
pub fn prepare_format_value(
    value: Value,
    format: OutputFormat,
    presentation: PresentationMode,
) -> Value {
    let scope = match format {
        OutputFormat::Json if presentation == PresentationMode::Agent => {
            Some(RedundancyScope::Machine)
        }
        OutputFormat::Json => None,
        OutputFormat::Auto | OutputFormat::Table if presentation != PresentationMode::Verbose => {
            Some(RedundancyScope::View)
        }
        OutputFormat::Auto | OutputFormat::Table => None,
    };
    match scope {
        Some(scope) => apply_redundancy_drop(value, scope),
        None => value,
    }
}

/// Apply format reductions to record metadata while preserving parsed bodies.
pub fn prepare_format_value_with_note_content(
    value: Value,
    format: OutputFormat,
    presentation: PresentationMode,
    content_scope: NoteContentScope,
) -> Value {
    let mut value = content_scope.protect(value, |value| {
        prepare_format_value(value, format, presentation)
    });
    if format == OutputFormat::Table {
        content_scope.stringify_table_content(&mut value);
    }
    value
}

// ── Redundancy-reduction pre-pass (ADR-078 §7, Amendment 3) ────────────────

/// Which redundancy-reduction rules apply (ADR-078 §7, Amendment 3).
///
/// `View` is the rendered-view scope (`auto`/`table`): the caller has opted
/// into a display form that is never chained on programmatically, so
/// `full_id` — the caller's stable chaining handle — is safe to drop along
/// with the other reductions.
///
/// `Machine` is the machine-contract scope (Agent `json`): this is the
/// default MCP response shape, the one a caller chains `$prev` and strict
/// verb parameters (`memory.feedback(target_id=...)`, `gtd.assign
/// (context_entity_id=...)`, etc.) from. It applies the `namespace` elision
/// and the `properties` dedup, but never drops `full_id`, and the
/// `properties` dedup itself exempts `full_id`/`ROUND_TRIP_FULL_UUID_FIELDS`
/// keys — a caller reading a strict identifier out of `properties` must see
/// the same canonical value there as at the top level. Dropping any of
/// those would return a value the strict verbs that consume it reject.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RedundancyScope {
    View,
    Machine,
}

/// Apply the redundancy-reduction pre-pass (ADR-078 §7, Amendment 3) to a
/// value at the given [`RedundancyScope`].
///
/// Applies at most ONE pass over the value. This function is the canonical
/// entry for the pre-pass; the per-record logic lives in `drop_record`.
///
/// Applied for Agent presentation in every format (`Machine` scope for
/// `json`, `View` scope for non-Verbose `auto`/`table`). Callers are
/// responsible for checking those conditions; this function applies
/// unconditionally.
pub fn apply_redundancy_drop(value: Value, scope: RedundancyScope) -> Value {
    match value {
        Value::Object(_) => drop_record(value, scope),
        Value::Array(arr) => Value::Array(
            arr.into_iter()
                .map(|v| {
                    if v.is_object() {
                        drop_record(v, scope)
                    } else {
                        v
                    }
                })
                .collect(),
        ),
        other => other,
    }
}

/// Apply per-record redundancy rules (§7.1, §7.2, §7.3) to a single record object.
fn drop_record(value: Value, scope: RedundancyScope) -> Value {
    let Value::Object(mut map) = value else {
        return value;
    };

    // `full_id` is a chaining handle. Dropping it is safe only in the View
    // scope (a rendered auto/table view the caller opted into); the Machine
    // scope (Agent JSON, the default machine contract) must keep it.
    if scope == RedundancyScope::View {
        map.remove("full_id");
    }

    // `"local"` is the common case, so only surface `namespace` when it isn't.
    if map.get("namespace").and_then(Value::as_str) == Some("local") {
        map.remove("namespace");
    }

    // Properties dedup: drop key-value pairs from `properties` that
    // duplicate an identical top-level sibling. The scalar hoist for table
    // columns lives in `hoist_table_scalars`, applied only on the table
    // path: reshaping the compact-JSON fallback would move fields with no
    // column to gain.
    //
    // Machine scope exempts `full_id`/`ROUND_TRIP_FULL_UUID_FIELDS`: a caller
    // that reads the strict identifier out of `properties` (rather than the
    // top-level convenience mirror) must keep getting the same canonical
    // value there too. View scope is unaffected — those callers already
    // opted into a display form, not the strict round-trip contract.
    let props_val = map.remove("properties");
    if let Some(Value::Object(props)) = props_val {
        let mut new_props = Map::new();
        for (k, v) in props {
            let strict_round_trip = scope == RedundancyScope::Machine
                && (k == "full_id" || ROUND_TRIP_FULL_UUID_FIELDS.contains(&k.as_str()));
            if !strict_round_trip && map.get(&k) == Some(&v) {
                continue;
            }
            new_props.insert(k, v);
        }
        if !new_props.is_empty() {
            map.insert("properties".to_string(), Value::Object(new_props));
        }
    } else if let Some(other) = props_val {
        map.insert("properties".to_string(), other);
    }

    // A stream entry's record is opaque caller JSON, including arrays of
    // objects whose fields happen to look like metadata.
    let stream_entry = is_stream_entry(&map);
    // Recurse into array values so nested record arrays are also reduced.
    let out: Map<String, Value> = map
        .into_iter()
        .map(|(k, v)| {
            if stream_entry && k == "record" {
                return (k, v);
            }
            let v = match v {
                Value::Array(arr) => Value::Array(
                    arr.into_iter()
                        .map(|item| {
                            if item.is_object() {
                                drop_record(item, scope)
                            } else {
                                item
                            }
                        })
                        .collect(),
                ),
                other => other,
            };
            (k, v)
        })
        .collect();
    Value::Object(out)
}

// ── Shape-aware rendering (`auto`) ──────────────────────────────────────────

/// A record array located inside a value: the records, their ordered column
/// keys, and — when the array sat under an object key — that key's name, so
/// the caller can enumerate the remaining (sibling) keys.
struct RecordArray {
    key: Option<String>,
    records: Vec<Value>,
    columns: Vec<String>,
}

/// Render a value using shape-aware dispatch (ADR-078 §3, as amended).
///
/// Shape (a): homogeneous record array → markdown table, with any envelope
/// siblings preserved as trailing `key: value` lines.
/// Every other shape → compact JSON, lossless by construction. The former
/// kv-block renderer for single records is removed: its truncation destroyed
/// single-record payloads (e.g. a compose briefing's `markdown` field).
fn render_auto(value: Value, truncate: bool) -> String {
    match locate_record_array(&value) {
        Some(found) => render_table_with_siblings(&value, &found, truncate),
        None => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
    }
}

/// Find the first homogeneous record array in `value`.
///
/// Checks:
/// 1. `value` itself is an array of 2+ objects.
/// 2. `value` is an object with a key whose value is an array of 2+ objects.
fn locate_record_array(value: &Value) -> Option<RecordArray> {
    let build = |key: Option<String>, arr: &[Value]| {
        let records: Vec<Value> = arr.iter().cloned().map(hoist_table_scalars).collect();
        let columns = collect_keys(&records);
        RecordArray {
            key,
            records,
            columns,
        }
    };
    match value {
        Value::Array(arr) if is_record_array(arr) => Some(build(None, arr)),
        Value::Object(map) => map.iter().find_map(|(k, v)| match v {
            Value::Array(arr) if is_record_array(arr) => Some(build(Some(k.clone()), arr)),
            _ => None,
        }),
        _ => None,
    }
}

/// Hoist `PROPERTY_HOIST_FIELDS` scalars out of a record's `properties` bag
/// to the top level (never overwriting a top-level sibling), so the table
/// renderer can surface them as columns — a scheduled event's
/// `trigger_at`/`status` live only inside `properties`, and a nested cell
/// renders as `{…}`. Table path only (ADR-078 Amendment 2): the compact-JSON
/// fallback keeps its shape.
fn hoist_table_scalars(record: Value) -> Value {
    let Value::Object(mut map) = record else {
        return record;
    };
    let mut props = match map.remove("properties") {
        Some(Value::Object(props)) => props,
        Some(other) => {
            // Non-object `properties` is not a bag to hoist from — restore it.
            map.insert("properties".to_string(), other);
            return Value::Object(map);
        }
        None => return Value::Object(map),
    };
    for field in PROPERTY_HOIST_FIELDS {
        if map.contains_key(*field) {
            continue;
        }
        if props
            .get(*field)
            .is_some_and(|v| !v.is_object() && !v.is_array())
        {
            let v = props.remove(*field).expect("checked above");
            map.insert((*field).to_string(), v);
        }
    }
    if !props.is_empty() {
        map.insert("properties".to_string(), Value::Object(props));
    }
    Value::Object(map)
}

/// An array of 2+ objects qualifies as a record array.
fn is_record_array(arr: &[Value]) -> bool {
    arr.len() >= 2 && arr.iter().all(Value::is_object)
}

/// Render the located record array as a table, then append one `key: value`
/// line per remaining top-level key. Envelope fields (`has_more`, `offset`,
/// counts) must survive rendering: dropping them made a truncated `query`
/// page read as complete.
fn render_table_with_siblings(value: &Value, found: &RecordArray, truncate: bool) -> String {
    let mut out = render_table(&found.records, &found.columns, truncate);
    let (Value::Object(map), Some(array_key)) = (value, &found.key) else {
        return out;
    };
    for (k, v) in map {
        if k == array_key {
            continue;
        }
        let text = match v {
            // A newline-bearing string renders as its JSON literal (one line,
            // lossless) so a stored value cannot fabricate a sibling line or
            // table row (ADR-078 Amendment 2 escaping contract).
            Value::String(s) if !s.contains(['\n', '\r']) => s.clone(),
            // Non-string scalars and nested values: compact JSON, untruncated
            // — sibling fidelity is the point of this path.
            other => serde_json::to_string(other).unwrap_or_default(),
        };
        out.push_str(&format!("{k}: {text}\n"));
    }
    out
}

/// Collect column names in first-seen order across all records.
fn collect_keys(records: &[Value]) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut keys = Vec::new();
    for record in records {
        if let Value::Object(map) = record {
            for k in map.keys() {
                if seen.insert(k.clone()) {
                    keys.push(k.clone());
                }
            }
        }
    }
    keys
}

// ── Markdown table renderer (ADR-078 §3a) ───────────────────────────────────

/// Render a record array as a GitHub-Flavored Markdown table.
fn render_table(records: &[Value], keys: &[String], truncate: bool) -> String {
    let mut out = String::new();

    out.push('|');
    for k in keys {
        out.push(' ');
        out.push_str(k);
        out.push_str(" |");
    }
    out.push('\n');

    out.push('|');
    for _ in keys {
        out.push_str("---|");
    }
    out.push('\n');

    for record in records {
        out.push('|');
        for k in keys {
            let cell = record.get(k).unwrap_or(&Value::Null);
            let text = cell_text(k, cell, truncate);
            out.push(' ');
            out.push_str(&text);
            out.push_str(" |");
        }
        out.push('\n');
    }

    out
}

/// Column names exempt from cell truncation: identity and decision fields
/// must arrive whole — a truncated id cannot be resolved and a truncated
/// title cannot be selected on.
fn truncation_exempt(key: &str) -> bool {
    matches!(
        key,
        "id" | "kind"
            | "status"
            | "priority"
            | "relation"
            | "title"
            | "name"
            | "signature"
            | "slug"
            | "assignee"
            | "from"
            | "to"
            | "due"
    ) || key.ends_with("_id")
        || key.ends_with("_at")
        || key.starts_with("due")
}

/// Format a cell value: escape `|`, collapse newlines, truncate to ~120 chars
/// unless `truncate` is off or the column is identity/decision-bearing.
///
/// Nested values are elided to a constant marker (`{…}` / `[…]`) rather than
/// stringified and cut mid-JSON: truncated pseudo-JSON reads as data while
/// silently missing fields. Full content is one `format=json` or `get` away.
fn cell_text(key: &str, value: &Value, truncate: bool) -> String {
    let raw = match value {
        Value::Null => String::new(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        Value::String(s) => s.clone(),
        Value::Object(_) => return "{…}".to_string(),
        Value::Array(arr) => {
            if arr.iter().any(|v| v.is_object() || v.is_array()) {
                return "[…]".to_string();
            }
            // Arrays of scalars (tags, ids) stay compact JSON.
            serde_json::to_string(value).unwrap_or_default()
        }
    };

    // Escape literal `|` and collapse embedded newlines to a space.
    let escaped = raw.replace('|', "\\|").replace(['\n', '\r'], " ");

    if !truncate || truncation_exempt(key) {
        return escaped;
    }

    // Truncate to approximately CELL_TRUNCATE *characters* (char boundary,
    // not byte index — slicing on a byte offset can panic on multi-byte chars).
    let char_count = escaped.chars().count();
    if char_count > CELL_TRUNCATE {
        let truncated: String = escaped.chars().take(CELL_TRUNCATE).collect();
        format!("{truncated}...")
    } else {
        escaped
    }
}

/// Format an instant in UTC using RFC3339 whole seconds and a `Z` suffix.
///
/// Fractional seconds are omitted. Chrono's supported years and signed
/// expanded-year rendering are inherited; no additional range validation is done.
/// Parsing and error policy remain with callers.
pub fn format_utc_rfc3339_seconds<Tz: chrono::TimeZone>(value: &chrono::DateTime<Tz>) -> String {
    value
        .with_timezone(&chrono::Utc)
        .to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}

/// Convert a microsecond epoch `i64` to an exact UTC ISO-8601 string.
///
/// Output always carries six fractional digits and a `Z` suffix. Years
/// 0000–9999 use the RFC 3339 spelling; other years use Chrono's signed
/// expanded-year convention. The full `i64` microsecond range is supported.
pub fn micros_to_iso(micros: i64) -> String {
    if let Some(dt) = chrono::DateTime::<chrono::Utc>::from_timestamp_micros(micros) {
        return dt.to_rfc3339_opts(chrono::SecondsFormat::Micros, true);
    }

    // Gregorian leap positions repeat every 400 years. Euclidean reduction
    // keeps the remainder in 1970–2369, including for negative timestamps.
    const CYCLE_MICROS: i64 = 146_097 * 86_400 * 1_000_000;
    let cycles = micros.div_euclid(CYCLE_MICROS);
    let reduced =
        chrono::DateTime::<chrono::Utc>::from_timestamp_micros(micros.rem_euclid(CYCLE_MICROS))
            .expect("400-year remainder is within Chrono's range");
    let year = i64::from(chrono::Datelike::year(&reduced)) + cycles * 400;
    let rendered = reduced.to_rfc3339_opts(chrono::SecondsFormat::Micros, true);
    format!("{year:+05}{}", &rendered[4..])
}

/// Parse an RFC 3339 timestamp (offset required) into microsecond epoch
/// `i64` — the inverse of [`micros_to_iso`] within the RFC 3339 four-digit
/// year range. Expanded ISO years are not accepted. This is the single parse
/// point for caller-supplied instants entering storage comparisons.
///
/// Leading/trailing whitespace is tolerated. Date-only and offset-less forms
/// are rejected; callers own the verb-specific error context around the
/// returned `ParseError`.
pub fn rfc3339_to_utc_micros(raw: &str) -> Result<i64, chrono::ParseError> {
    chrono::DateTime::parse_from_rfc3339(raw.trim()).map(|dt| dt.timestamp_micros())
}

/// How the response envelope is presented to the caller.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum PresentationMode {
    /// Token-efficient. Default for MCP callers (agents).
    ///
    /// Short UUIDs (8-char), exact UTC timestamps with relative labels on
    /// list rows, empty fields dropped, structural nulls preserved, and
    /// score fields truncated to 3 significant figures.
    #[default]
    Agent,
    /// Full canonical shape. Default for `kkernel exec` and CI/scripted callers.
    ///
    /// No transformation — handler output passes through as-is.
    Verbose,
    /// Pretty-printed terminal output. Default for `khive` CLI.
    ///
    /// **At the MCP runtime level this is identical to `Verbose`** — the
    /// canonical JSON is returned unchanged. Terminal formatting (relative
    /// timestamps, glyph substitution, table layout) is applied by the CLI
    /// layer (`khive-cli::format::pretty`), not the MCP response pipeline.
    Human,
}

/// Lifecycle/operational `null` fields that are PRESERVED in Agent mode.
///
/// These fields carry state meaning (absent ≠ known-unknown) and must not be
/// dropped. The channel-health fields distinguish a quarantine-only identity
/// from a heartbeat row whose liveness facts were actually observed.
const LIFECYCLE_NULL_PRESERVE: &[&str] = &[
    "completed_at",
    "deleted_at",
    "due_at",
    "read_at",
    "started_at",
    "superseded_at",
    "applied_at",
    "withdrawn_at",
    "reviewed_at",
    "parent_id",
    "superseded_by",
    "replaced_by",
    "poll_interval_secs",
    "stalled",
    "last_success_at",
    "last_poll_attempt_at",
    "last_failure_at",
    "last_error",
    "consecutive_failures",
];

/// Empty collection fields that define a stable response envelope and must
/// survive Agent-mode compaction. Dropping these turns an empty page into a
/// different response type and leaves callers unable to distinguish an empty
/// result from a missing/unsupported field.
const EMPTY_ARRAY_PRESERVE: &[&str] = &[
    "items",
    "entities",
    "notes",
    "edges",
    "results",
    "entries",
    "neighbors",
];

fn is_stable_list_envelope(map: &Map<String, Value>) -> bool {
    map.contains_key("requested_limit")
        && map.contains_key("effective_limit")
        && map.contains_key("limit_clamped")
        && EMPTY_ARRAY_PRESERVE
            .iter()
            .any(|field| map.contains_key(*field))
}

/// Keyset cursor pages outside the ADR-023 envelope — `knowledge.list(after=…)`
/// returns `{results, limit, order, next_after}` — are structural in the same
/// way (ADR-045 Amendment 4): an empty `results` page and a terminal
/// `next_after: null` are the walk's completion signals, so a caller that
/// cannot see them cannot stop. A `results` array without a sibling
/// `next_after` key is an ordinary response and gets the generic transform.
fn is_keyset_cursor_envelope(map: &Map<String, Value>) -> bool {
    map.contains_key("next_after")
        && (map.get("results").is_some_and(Value::is_array)
            || (map.get("head_seq").is_some_and(Value::is_number)
                && map.get("entries").is_some_and(Value::is_array)))
}

fn is_stream_entry(map: &Map<String, Value>) -> bool {
    map.get("seq").is_some_and(Value::is_number)
        && map.contains_key("id")
        && map.contains_key("created_at")
        && map.contains_key("record")
}

/// Field names carrying caller-supplied payload timestamps that must never be
/// transformed, regardless of nesting.
///
/// These encode domain semantics the caller needs to round-trip verbatim —
/// e.g. `trigger_at` on a `schedule.remind`/`schedule.schedule` create
/// response, returned as a top-level convenience field alongside `id` and
/// `full_id`, not nested under `"properties"`. The `inside_properties` guard
/// alone only protects fields nested under a literal `"properties"` key
/// (as returned by `agenda`/`get`); it does not cover this top-level case,
/// which older Agent presentation rewrote into a relative or minute-truncated
/// form, discarding the seconds and offset needed for round trips (#871).
///
/// `due` on `gtd.assign`/`gtd.tasks`/`gtd.next` responses is the same shape:
/// a top-level convenience field mirroring `properties.due`, which
/// `parse_due` already normalizes to full RFC 3339.
const PAYLOAD_TIMESTAMP_FIELDS: &[&str] = &["trigger_at", "due"];

/// UUID fields whose canonical value is itself a strict-verb input.
///
/// Shortening these would make a successful response fail when submitted back
/// to the verb that produced or consumes it. `context_entity_id` and
/// `thread_id` are explicit stable references rather than prefix searches;
/// `outbound_ref` is the exact correlation key consumed by `comm.delivered`;
/// `parent_id` is the explicit ancestry reference consumed by `propose`;
/// `session_id` is an exact event-list filter; and `project_id` is the exact
/// provenance anchor required by git issue and pull-request creation.
const ROUND_TRIP_FULL_UUID_FIELDS: &[&str] = &[
    "context_entity_id",
    "thread_id",
    "outbound_ref",
    "parent_id",
    "session_id",
    "project_id",
];

/// Score field names that are truncated to 3 significant figures in Agent mode.
const SCORE_FIELDS: &[&str] = &[
    "score",
    "rank_score",
    "vector_similarity",
    "keyword_score",
    "salience",
    "decay_factor",
    "rrf_score",
    "similarity",
    "cross_encoder_score",
    "graph_proximity_score",
];

/// UUID v4 canonical string length (8-4-4-4-12 = 32 hex + 4 dashes = 36).
const UUID_CANONICAL_LEN: usize = 36;

/// Return true for fields whose whole-string UUID values may be shortened in
/// Agent mode. Content-like fields are intentionally excluded even when their
/// value happens to be UUID-shaped.
///
/// `full_id` and strict round-trip fields are explicitly excluded: their
/// purpose is to give callers a stable chaining handle, so shortening them
/// would produce a value that the corresponding strict verb rejects.
fn should_shorten_uuid_field(key: &str) -> bool {
    if key == "full_id" || key == "bridge_instance_id" || ROUND_TRIP_FULL_UUID_FIELDS.contains(&key)
    {
        return false;
    }
    key == "id" || key.ends_with("_id") || matches!(key, "superseded_by" | "replaced_by")
}

/// Transform a successful verb result value according to the given
/// [`PresentationMode`].
///
/// - `Verbose` / `Human`: returns `value` unchanged.
/// - `Agent`: applies UUID shortening, exact UTC timestamp rendering, empty-field
///   dropping, structural-null preservation, and score truncation.
///
/// `now_unix_seconds` is a whole-second clock for callers without a finer
/// sample. All relative list-row labels within a response use this instant.
pub fn present(value: Value, mode: PresentationMode, now_unix_seconds: i64) -> Value {
    present_with_policy(
        value,
        mode,
        now_unix_seconds,
        VerbPresentationPolicy::Standard,
    )
}

/// Present a successful result using its trusted registered verb policy.
/// Receipt policies preserve only their closed string paths, not descendants.
pub fn present_with_policy(
    value: Value,
    mode: PresentationMode,
    now_unix_seconds: i64,
    policy: VerbPresentationPolicy,
) -> Value {
    present_with_policy_at(value, mode, now_unix_seconds.into(), policy)
}

/// A response-wide clock sample. Fractional precision distinguishes a newly
/// stored row from a truly future row within the same Unix second.
#[derive(Clone, Copy)]
pub struct PresentationNow {
    seconds: i64,
    nanoseconds: u32,
}

impl From<i64> for PresentationNow {
    fn from(seconds: i64) -> Self {
        Self {
            seconds,
            nanoseconds: 0,
        }
    }
}

impl From<i32> for PresentationNow {
    fn from(seconds: i32) -> Self {
        i64::from(seconds).into()
    }
}

impl From<chrono::DateTime<chrono::Utc>> for PresentationNow {
    fn from(now: chrono::DateTime<chrono::Utc>) -> Self {
        Self {
            seconds: now.timestamp(),
            nanoseconds: now.timestamp_subsec_nanos(),
        }
    }
}

/// Present with the response's single sampled instant, including its fraction.
pub fn present_with_policy_at(
    value: Value,
    mode: PresentationMode,
    now: PresentationNow,
    policy: VerbPresentationPolicy,
) -> Value {
    if policy == VerbPresentationPolicy::AlwaysVerbose {
        return value;
    }
    match mode {
        PresentationMode::Verbose | PresentationMode::Human => value,
        PresentationMode::Agent => {
            // These root paths are selected by the registered agenda handler,
            // never by a payload marker or a nested lookalike. The cursor's
            // timestamp spelling and full UUID jointly define its seek position.
            let mut value = value;
            let agenda_next = (policy == VerbPresentationPolicy::AgendaContinuation)
                .then(|| value.as_object_mut().and_then(|map| map.remove("next")))
                .flatten();
            let agenda_empty = policy == VerbPresentationPolicy::AgendaContinuation
                && value
                    .get("events")
                    .and_then(Value::as_array)
                    .is_some_and(Vec::is_empty);
            let config = AgentTransformConfig {
                preserved_nulls: LIFECYCLE_NULL_PRESERVE.iter().copied().collect(),
                scores: SCORE_FIELDS.iter().copied().collect(),
                payload_timestamps: PAYLOAD_TIMESTAMP_FIELDS.iter().copied().collect(),
                now,
            };
            let mut value = transform_agent(
                value,
                &config,
                AgentTreeContext {
                    inside_properties: false,
                    object_properties: false,
                    array_member: false,
                    receipt_context: match policy {
                        VerbPresentationPolicy::StreamAppendReceipt => ReceiptContext::AppendRoot,
                        VerbPresentationPolicy::StreamBatchReceipts => ReceiptContext::BatchRoot,
                        _ => ReceiptContext::None,
                    },
                },
            );
            if let Some(map) = value.as_object_mut() {
                if let Some(next) = agenda_next {
                    map.insert("next".into(), next);
                }
                if agenda_empty {
                    map.insert("events".into(), Value::Array(Vec::new()));
                }
            }
            value
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum ReceiptContext {
    None,
    AppendRoot,
    BatchRoot,
    BatchResults,
    BatchMember,
}

struct AgentTransformConfig {
    preserved_nulls: HashSet<&'static str>,
    scores: HashSet<&'static str>,
    payload_timestamps: HashSet<&'static str>,
    now: PresentationNow,
}

#[derive(Clone, Copy)]
struct AgentTreeContext {
    inside_properties: bool,
    object_properties: bool,
    array_member: bool,
    receipt_context: ReceiptContext,
}

/// Apply the Agent-mode transform to an arbitrary JSON value.
///
/// `inside_properties` is `true` when recursing inside a `"properties"` value.
/// Caller-supplied payload timestamps (e.g. `trigger_at`) must not be normalized
/// because they encode domain semantics the agent may need to round-trip.
fn transform_agent(
    value: Value,
    config: &AgentTransformConfig,
    context: AgentTreeContext,
) -> Value {
    match value {
        Value::Object(map) => {
            let preserve_list_envelope =
                is_stable_list_envelope(&map) || is_keyset_cursor_envelope(&map);
            let stream_entry = is_stream_entry(&map);
            let relative_created_at = (context.array_member
                && !context.inside_properties
                && !map.contains_key("created_at_relative")
                && !matches!(
                    context.receipt_context,
                    ReceiptContext::AppendRoot | ReceiptContext::BatchMember
                ))
            .then(|| map.get("created_at").and_then(Value::as_str))
            .flatten()
            .and_then(|raw| {
                let (_, created_at) = exact_timestamp(raw)?;
                let age = config.now.seconds.checked_sub(created_at)?;
                // Floor the full fractional age. The lexicographic comparison
                // also handles canonical fractions longer than nanoseconds.
                age.checked_sub(i64::from(
                    timestamp_fraction_cmp(raw, config.now.nanoseconds) == Ordering::Greater,
                ))
            })
            .filter(|difference| *difference >= 0)
            .map(relative_time);
            let mut out = Map::new();
            for (k, v) in map {
                if stream_entry && k == "record" {
                    out.insert(k, v);
                    continue;
                }
                if v.is_string()
                    && ((context.receipt_context == ReceiptContext::AppendRoot
                        && k == "created_at")
                        || (context.receipt_context == ReceiptContext::BatchMember
                            && matches!(k.as_str(), "created_at" | "updated_at")))
                {
                    out.insert(k, v);
                    continue;
                }
                let child_receipt_context = if context.receipt_context == ReceiptContext::BatchRoot
                    && k == "results"
                    && v.is_array()
                {
                    ReceiptContext::BatchResults
                } else {
                    ReceiptContext::None
                };
                // ADR-045 Amendment 3 scopes the empty-string carve-out to
                // strings nested under an object-valued `properties`; a
                // scalar or array `properties` value gets no carve-out.
                let child_inside_properties = context.inside_properties || k == "properties";
                let child_object_properties =
                    context.object_properties || (k == "properties" && v.is_object());
                let transformed = transform_field_agent(
                    &k,
                    v,
                    config,
                    AgentFieldContext {
                        inside_properties: child_inside_properties,
                        object_properties: child_object_properties,
                        preserve_list_envelope,
                        receipt_context: child_receipt_context,
                    },
                );
                match transformed {
                    None => {} // drop
                    Some(tv) => {
                        out.insert(k, tv);
                    }
                }
            }
            if let Some(relative) = relative_created_at {
                out.insert("created_at_relative".to_string(), Value::String(relative));
            }
            Value::Object(out)
        }
        Value::Array(arr) => {
            let items: Vec<Value> = arr
                .into_iter()
                .map(|v| {
                    transform_agent(
                        v,
                        config,
                        AgentTreeContext {
                            inside_properties: context.inside_properties,
                            object_properties: context.object_properties,
                            array_member: true,
                            receipt_context: if context.receipt_context
                                == ReceiptContext::BatchResults
                            {
                                ReceiptContext::BatchMember
                            } else {
                                ReceiptContext::None
                            },
                        },
                    )
                })
                .collect();
            Value::Array(items)
        }
        other => other,
    }
}

/// Transform a single named field value under Agent mode.
///
/// Returns `None` if the field should be dropped.
///
/// `inside_properties` suppresses timestamp normalization for caller-submitted
/// payload values nested under a literal `"properties"` key (e.g. `trigger_at`
/// as returned by `agenda`/`get`). `payload_timestamps` suppresses normalization
/// by field name regardless of nesting, covering top-level convenience fields
/// such as the `trigger_at` returned directly in a `schedule.remind`/
/// `schedule.schedule` create response (#871). Metadata timestamps at the top
/// level (`created_at`, `updated_at`) still render as exact UTC instants.
#[derive(Clone, Copy)]
struct AgentFieldContext {
    inside_properties: bool,
    object_properties: bool,
    preserve_list_envelope: bool,
    receipt_context: ReceiptContext,
}

fn transform_field_agent(
    key: &str,
    value: Value,
    config: &AgentTransformConfig,
    context: AgentFieldContext,
) -> Option<Value> {
    match &value {
        // Preserve lifecycle and stable-envelope nulls; drop other nulls.
        Value::Null => {
            if config.preserved_nulls.contains(key)
                || (context.preserve_list_envelope && key == "next_after")
            {
                Some(value)
            } else {
                None
            }
        }
        // Stable page-envelope arrays remain present even when empty.
        Value::Array(a)
            if context.preserve_list_envelope
                && a.is_empty()
                && EMPTY_ARRAY_PRESERVE.contains(&key) =>
        {
            Some(value)
        }
        // Preserve empty strings under a record's `properties` object: those
        // keys exist only because a caller wrote them, so `""` there is data
        // (set-to-empty vs absent, ADR-045 Amendment 3, issue #1995). Empty
        // arrays and objects under `properties` are still dropped per the
        // amendment's scope note.
        Value::String(s) if s.is_empty() && context.object_properties => Some(value),
        // Drop other empty strings, arrays, objects.
        Value::String(s) if s.is_empty() => None,
        Value::Array(a) if a.is_empty() => None,
        Value::Object(o) if o.is_empty() => None,
        // Truncate score fields.
        Value::Number(_) if config.scores.contains(key) => {
            if let Some(f) = value.as_f64() {
                Some(truncate_to_3_sig_figs(f))
            } else {
                Some(value)
            }
        }
        // Shorten UUIDs only in fields whose names carry ID semantics.
        Value::String(s) if is_canonical_uuid(s) && should_shorten_uuid_field(key) => {
            Some(Value::String(s[..8].to_string()))
        }
        // Render whole, offset-bearing timestamps in exact UTC form unless
        // this is caller-supplied or otherwise protected payload data.
        Value::String(s)
            if !context.inside_properties
                && !config.payload_timestamps.contains(key)
                && looks_like_iso8601(s) =>
        {
            Some(Value::String(
                exact_timestamp(s).map_or_else(|| s.clone(), |(rendered, _)| rendered),
            ))
        }
        // Recurse into objects and arrays.
        Value::Object(_) | Value::Array(_) => Some(transform_agent(
            value,
            config,
            AgentTreeContext {
                inside_properties: context.inside_properties,
                object_properties: context.object_properties,
                array_member: false,
                receipt_context: context.receipt_context,
            },
        )),
        // Everything else passes through.
        _ => Some(value),
    }
}

/// Returns `true` if `s` looks like a canonical UUID (36 chars, standard form).
fn is_canonical_uuid(s: &str) -> bool {
    if s.len() != UUID_CANONICAL_LEN {
        return false;
    }
    let b = s.as_bytes();
    // Pattern: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
    b[8] == b'-'
        && b[13] == b'-'
        && b[18] == b'-'
        && b[23] == b'-'
        && b[..8].iter().all(|c| c.is_ascii_hexdigit())
        && b[9..13].iter().all(|c| c.is_ascii_hexdigit())
        && b[14..18].iter().all(|c| c.is_ascii_hexdigit())
        && b[19..23].iter().all(|c| c.is_ascii_hexdigit())
        && b[24..].iter().all(|c| c.is_ascii_hexdigit())
}

/// Returns `true` if `s` looks like an ISO-8601 datetime string.
///
/// Heuristic: starts with `YYYY-MM-DDTHH:` (16 chars, proper digit positions).
fn looks_like_iso8601(s: &str) -> bool {
    if s.len() < 16 {
        return false;
    }
    let b = s.as_bytes();
    b[4] == b'-'
        && b[7] == b'-'
        && b[10] == b'T'
        && b[13] == b':'
        && b[..4].iter().all(|c| c.is_ascii_digit())
        && b[5..7].iter().all(|c| c.is_ascii_digit())
        && b[8..10].iter().all(|c| c.is_ascii_digit())
        && b[11..13].iter().all(|c| c.is_ascii_digit())
}

/// Render a whole timestamp in UTC while retaining its original fraction digits.
fn exact_timestamp(s: &str) -> Option<(String, i64)> {
    let unix = parse_iso8601_unix(s)?;
    let tail = s.get(19..)?;
    let fraction = if let Some(after_dot) = tail.strip_prefix('.') {
        let digits = after_dot.bytes().take_while(u8::is_ascii_digit).count();
        tail.get(..digits + 1)?
    } else {
        ""
    };
    let utc = chrono::DateTime::<chrono::Utc>::from_timestamp(unix, 0)?;
    Some((
        format!("{}{fraction}Z", utc.format("%Y-%m-%dT%H:%M:%S")),
        unix,
    ))
}

/// Compare the timestamp's decimal fraction with a sampled nanosecond value.
/// Digits beyond nanoseconds matter when the leading nine digits tie.
fn timestamp_fraction_cmp(timestamp: &str, now_nanoseconds: u32) -> Ordering {
    let fraction = if timestamp.as_bytes().get(19) == Some(&b'.') {
        timestamp.as_bytes()[20..]
            .split(|byte| !byte.is_ascii_digit())
            .next()
            .unwrap_or_default()
    } else {
        &[]
    };
    let now_fraction = format!("{now_nanoseconds:09}");
    for index in 0..fraction.len().max(9) {
        let created_digit = fraction.get(index).copied().unwrap_or(b'0');
        let now_digit = now_fraction.as_bytes().get(index).copied().unwrap_or(b'0');
        match created_digit.cmp(&now_digit) {
            Ordering::Equal => {}
            difference => return difference,
        }
    }
    Ordering::Equal
}

/// Parse a whole ISO-8601 datetime with an explicit offset to Unix seconds.
///
/// Accepts `YYYY-MM-DDTHH:MM:SS[.frac](Z|±HH:MM|±HHMM)`. An offset-less,
/// invalid or trailing-text value stays byte-exact in Agent presentation.
fn parse_iso8601_unix(s: &str) -> Option<i64> {
    if s.len() < 20 {
        return None;
    }
    let b = s.as_bytes();
    if b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' {
        return None;
    }
    let year: i64 = parse_digits(&b[0..4])?;
    let month: i64 = parse_digits(&b[5..7])?;
    let day: i64 = parse_digits(&b[8..10])?;
    let hour: i64 = parse_digits(&b[11..13])?;
    let minute: i64 = parse_digits(&b[14..16])?;
    let second: i64 = parse_digits(&b[17..19])?;

    let local = chrono::NaiveDate::from_ymd_opt(
        year.try_into().ok()?,
        month.try_into().ok()?,
        day.try_into().ok()?,
    )?
    .and_hms_opt(
        hour.try_into().ok()?,
        minute.try_into().ok()?,
        second.try_into().ok()?,
    )?
    .and_utc()
    .timestamp();
    let offset_secs = parse_tz_offset_secs(s.get(19..)?)?;
    local.checked_sub(offset_secs)
}

/// Parse the tail of an ISO-8601 timestamp (everything from byte index 19
/// onward, i.e. after the whole-seconds field) into a UTC offset in seconds.
///
/// Handles, in order: optional fractional seconds (`.nnn`, skipped — this
/// parser only has whole-second precision), then one of:
/// - `"Z"` → offset 0
/// - `±HH:MM` or the compact `±HHMM` form → `sign * (hh*3600 + mm*60)`
///
/// Returns `None` for anything else (malformed tail).
fn parse_tz_offset_secs(tail: &str) -> Option<i64> {
    let mut rest = tail;
    if let Some(after_dot) = rest.strip_prefix('.') {
        let frac_len = after_dot.bytes().take_while(u8::is_ascii_digit).count();
        if frac_len == 0 {
            return None;
        }
        rest = &after_dot[frac_len..];
    }

    if rest == "Z" {
        return Some(0);
    }

    let sign: i64 = match rest.as_bytes().first()? {
        b'+' => 1,
        b'-' => -1,
        _ => return None,
    };
    let digits = &rest[1..];
    let (hh, mm) = match digits.len() {
        // "HH:MM"
        5 if digits.as_bytes()[2] == b':' => (
            parse_digits(&digits.as_bytes()[0..2])?,
            parse_digits(&digits.as_bytes()[3..5])?,
        ),
        // "HHMM"
        4 => (
            parse_digits(&digits.as_bytes()[0..2])?,
            parse_digits(&digits.as_bytes()[2..4])?,
        ),
        _ => return None,
    };
    if hh > 23 || mm > 59 {
        return None;
    }
    Some(sign * (hh * 3600 + mm * 60))
}

fn parse_digits(b: &[u8]) -> Option<i64> {
    let s = std::str::from_utf8(b).ok()?;
    s.parse().ok()
}

/// Format a duration in seconds as a relative time string (e.g. `"3m ago"`).
fn relative_time(diff_secs: i64) -> String {
    if diff_secs < 60 {
        format!("{diff_secs}s ago")
    } else if diff_secs < 3600 {
        format!("{}m ago", diff_secs / 60)
    } else if diff_secs < 86400 {
        format!("{}h ago", diff_secs / 3600)
    } else {
        format!("{}d ago", diff_secs / 86400)
    }
}

/// Truncate a float to 3 significant figures, returning a `serde_json::Value`.
fn truncate_to_3_sig_figs(f: f64) -> Value {
    if f == 0.0 || !f.is_finite() {
        return Value::from(f);
    }
    let magnitude = f.abs().log10().floor() as i32;
    let factor = 10f64.powi(2 - magnitude);
    let rounded = (f * factor).round() / factor;
    // Re-serialize through serde_json to avoid floating-point noise.
    serde_json::Number::from_f64(rounded)
        .map(Value::Number)
        .unwrap_or(Value::from(rounded))
}

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

    /// A fixed "now" for deterministic tests: 2025-05-23T16:08:00Z.
    const NOW: i64 = 1_748_016_480;

    #[test]
    fn utc_rfc3339_seconds_normalizes_offsets_and_omits_fractions() {
        for (raw, expected) in [
            (
                "2026-01-01T00:15:30.987654321+01:00",
                "2025-12-31T23:15:30Z",
            ),
            ("1969-12-31T23:59:59.999999999Z", "1969-12-31T23:59:59Z"),
        ] {
            let instant = chrono::DateTime::parse_from_rfc3339(raw).unwrap();
            assert_eq!(format_utc_rfc3339_seconds(&instant), expected, "{raw}");
        }
    }

    #[test]
    fn micros_to_iso_preserves_chrono_range_spelling() {
        for (micros, expected) in [
            (0, "1970-01-01T00:00:00.000000Z"),
            (-1, "1969-12-31T23:59:59.999999Z"),
            (1_748_016_480_123_456, "2025-05-23T16:08:00.123456Z"),
            (-62_198_755_200_000_000, "-0001-01-01T00:00:00.000000Z"),
            (253_402_300_800_000_000, "+10000-01-01T00:00:00.000000Z"),
            (-8_334_601_228_800_000_000, "-262143-01-01T00:00:00.000000Z"),
            (8_210_266_876_799_999_999, "+262142-12-31T23:59:59.999999Z"),
        ] {
            assert!(
                chrono::DateTime::<chrono::Utc>::from_timestamp_micros(micros).is_some(),
                "{micros}"
            );
            assert_eq!(micros_to_iso(micros), expected, "{micros}");
        }
    }

    #[test]
    fn micros_to_iso_formats_outside_chrono_range_exactly() {
        for (micros, expected) in [
            (i64::MIN, "-290308-12-21T19:59:05.224192Z"),
            (i64::MAX, "+294247-01-10T04:00:54.775807Z"),
            (-8_334_601_228_800_000_001, "-262144-12-31T23:59:59.999999Z"),
            (8_210_266_876_800_000_000, "+262143-01-01T00:00:00.000000Z"),
            (-8_898_108_636_303_876_544, "-280000-02-29T12:34:56.123456Z"),
            (8_776_940_198_400_000_001, "+280100-03-01T00:00:00.000001Z"),
        ] {
            assert!(
                chrono::DateTime::<chrono::Utc>::from_timestamp_micros(micros).is_none(),
                "{micros}"
            );
            assert_eq!(micros_to_iso(micros), expected, "{micros}");
        }
    }

    #[test]
    fn expanded_micros_timestamps_pass_through_agent_without_relative_labels() {
        for (micros, expected) in [
            (i64::MIN, "-290308-12-21T19:59:05.224192Z"),
            (i64::MAX, "+294247-01-10T04:00:54.775807Z"),
        ] {
            let shown = present(
                json!({"items": [{"created_at": micros_to_iso(micros)}]}),
                PresentationMode::Agent,
                NOW,
            );
            assert_eq!(shown, json!({"items": [{"created_at": expected}]}));
            assert!(rfc3339_to_utc_micros(expected).is_err());
        }
    }

    #[test]
    fn rfc3339_to_utc_micros_round_trips_and_rejects_partial_forms() {
        let micros = 1_748_016_480_000_000_i64;
        assert_eq!(rfc3339_to_utc_micros(&micros_to_iso(micros)), Ok(micros));
        // Offset spellings resolve to the same instant; whitespace tolerated.
        // The offset spelling names the same instant as NOW.
        assert_eq!(
            rfc3339_to_utc_micros(" 2025-05-23T12:08:00-04:00 "),
            Ok(micros)
        );
        assert!(rfc3339_to_utc_micros("2026-05-23").is_err());
        assert!(rfc3339_to_utc_micros("2026-05-23T16:18:00").is_err());
    }

    fn agent(v: Value) -> Value {
        present(v, PresentationMode::Agent, NOW)
    }

    #[test]
    fn agent_preserves_empty_string_under_properties() {
        // ADR-045 Amendment 3 (issue #1995): a key under `properties` exists
        // only because a caller wrote it, so `""` there distinguishes
        // set-to-empty from absent and must survive Agent mode — at any
        // nesting depth under `properties`.
        let v = json!({
            "id": "a1b2c3d4",
            "summary": "",
            "properties": {"k": "", "nested": {"deep": ""}},
        });
        let out = agent(v);
        assert_eq!(out["properties"]["k"], json!(""));
        assert_eq!(out["properties"]["nested"]["deep"], json!(""));
        // Control: outside `properties` the empty-string drop still applies.
        assert!(out.get("summary").is_none());
    }

    #[test]
    fn agent_drops_scalar_empty_properties_value() {
        // The carve-out applies only to strings nested under an object-valued
        // `properties`; a scalar `properties: ""` is the field's own value,
        // not a caller-written key under it, and drops like any empty string.
        let v = json!({
            "id": "a1b2c3d4",
            "properties": "",
        });
        let out = agent(v);
        assert!(out.get("properties").is_none());
    }

    #[test]
    fn agent_still_drops_empty_containers_under_properties() {
        // The amendment's scope note keeps the container drop: empty arrays
        // and objects under `properties` are not carved out.
        let v = json!({
            "id": "a1b2c3d4",
            "properties": {"tags": [], "meta": {}, "kept": "x"},
        });
        let out = agent(v);
        assert!(out["properties"].get("tags").is_none());
        assert!(out["properties"].get("meta").is_none());
        assert_eq!(out["properties"]["kept"], json!("x"));
    }

    #[test]
    fn verbose_passthrough() {
        let v = json!({"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "title": "X"});
        let out = present(v.clone(), PresentationMode::Verbose, NOW);
        assert_eq!(out, v);
    }

    #[test]
    fn agent_shortens_uuid() {
        let v = json!({"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"});
        let out = agent(v);
        assert_eq!(out["id"], json!("a1b2c3d4"));
    }

    #[test]
    fn agent_drops_empty_string() {
        let v = json!({"title": "ok", "description": ""});
        let out = agent(v);
        assert!(out.get("description").is_none());
        assert_eq!(out["title"], json!("ok"));
    }

    #[test]
    fn agent_drops_empty_array() {
        let v = json!({"tags": [], "title": "ok"});
        let out = agent(v);
        assert!(out.get("tags").is_none());
    }

    #[test]
    fn agent_preserves_empty_list_page_arrays() {
        let v = json!({
            "items": [],
            "entities": [],
            "notes": [],
            "edges": [],
            "results": [],
            "entries": [],
            "neighbors": [],
            "next_after": null,
            "requested_limit": 10,
            "effective_limit": 10,
            "limit_clamped": false,
        });
        let out = agent(v);
        for key in EMPTY_ARRAY_PRESERVE {
            assert_eq!(out[*key], json!([]), "missing structural key {key}");
        }
        assert_eq!(out["next_after"], json!(null));
    }

    #[test]
    fn agent_preserves_keyset_cursor_envelope_completion_signals() {
        // knowledge.list(after=…) terminal/empty page: both signals survive.
        let out = agent(json!({
            "results": [],
            "limit": 500,
            "order": "created_at ASC, id ASC",
            "next_after": null,
        }));
        assert_eq!(out["results"], json!([]));
        assert!(
            out.get("next_after").is_some_and(Value::is_null),
            "terminal cursor page must keep next_after:null: {out}"
        );
    }

    #[test]
    fn agent_results_without_next_after_is_not_a_cursor_envelope() {
        let out = agent(json!({"results": [], "limit": 500, "title": "ordinary response"}));
        assert!(out.get("results").is_none());
    }

    #[test]
    fn agent_still_drops_empty_arrays_outside_list_envelopes() {
        let out = agent(json!({"items": [], "entities": [], "title": "ordinary response"}));
        assert!(out.get("items").is_none());
        assert!(out.get("entities").is_none());
    }

    #[test]
    fn agent_drops_empty_object() {
        let v = json!({"properties": {}, "title": "ok"});
        let out = agent(v);
        assert!(out.get("properties").is_none());
    }

    #[test]
    fn agent_drops_non_lifecycle_null() {
        let v = json!({"result": null, "title": "ok"});
        let out = agent(v);
        assert!(out.get("result").is_none());
    }

    #[test]
    fn agent_preserves_lifecycle_null() {
        let v = json!({"completed_at": null, "due_at": null, "title": "ok"});
        let out = agent(v);
        assert_eq!(out["completed_at"], json!(null));
        assert_eq!(out["due_at"], json!(null));
    }

    #[test]
    fn agent_preserves_relationship_null() {
        let v = json!({"parent_id": null, "superseded_by": null});
        let out = agent(v);
        assert_eq!(out["parent_id"], json!(null));
        assert_eq!(out["superseded_by"], json!(null));
    }

    #[test]
    fn agent_preserves_unknown_channel_heartbeat_nulls() {
        let v = json!({
            "channels": [{
                "poll_interval_secs": null,
                "stalled": null,
                "last_success_at": null,
                "last_poll_attempt_at": null,
                "last_failure_at": null,
                "last_error": null,
                "consecutive_failures": null,
                "quarantined_count": 1,
            }]
        });
        let out = agent(v);
        let channel = out["channels"][0].as_object().expect("channel object");
        for field in [
            "poll_interval_secs",
            "stalled",
            "last_success_at",
            "last_poll_attempt_at",
            "last_failure_at",
            "last_error",
            "consecutive_failures",
        ] {
            assert_eq!(
                channel.get(field),
                Some(&Value::Null),
                "Agent presentation must preserve unknown heartbeat fact `{field}`"
            );
        }
    }

    #[test]
    fn agent_truncates_score_field() {
        let v = json!({"score": 0.12345678});
        let out = agent(v);
        let s = out["score"].as_f64().unwrap();
        assert!((s - 0.123).abs() < 1e-9, "expected ~0.123, got {s}");
    }

    #[test]
    fn agent_presents_ranking_alias_and_nested_evidence() {
        let canonical = json!([
            {
                "rank_score": 0.0325224749,
                "score": 0.0325224749,
                "rank_score_kind": "rrf",
                "signals": {"vector_similarity": 0.842567, "keyword_score": 18.375}
            },
            {"rank_score": 0.0, "score": 0.0, "rank_score_kind": "keyword", "signals": {}}
        ]);
        for mode in [PresentationMode::Verbose, PresentationMode::Human] {
            assert_eq!(present(canonical.clone(), mode, NOW), canonical);
        }
        let shown = agent(canonical);
        assert_eq!(shown[0]["rank_score"], json!(0.0325));
        assert_eq!(shown[0]["score"], shown[0]["rank_score"]);
        assert_eq!(shown[0]["rank_score_kind"], "rrf");
        assert_eq!(shown[0]["signals"]["vector_similarity"], json!(0.843));
        assert_eq!(shown[0]["signals"]["keyword_score"], json!(18.4));
        assert_eq!(shown[1]["rank_score"], json!(0.0));
        assert_eq!(shown[1]["score"], shown[1]["rank_score"]);
        assert_eq!(shown[1]["rank_score_kind"], "keyword");
        assert!(shown[1].get("signals").is_none());
    }

    #[test]
    fn agent_renders_old_timestamp_exactly() {
        let v = json!({"created_at": "2020-01-01T10:30:45.123456Z"});
        let out = agent(v);
        assert_eq!(out["created_at"], json!("2020-01-01T10:30:45.123456Z"));
        assert!(out.get("created_at_relative").is_none());
    }

    #[test]
    fn agent_renders_recent_timestamp_exactly() {
        let ts_unix = NOW - 180;
        let ts = unix_to_iso8601(ts_unix);
        let v = json!({"updated_at": ts.clone()});
        let out = agent(v);
        assert_eq!(out["updated_at"], json!(ts));
    }

    #[test]
    fn agent_does_not_compact_top_level_trigger_at_field() {
        // Regression for #871: `schedule.remind`'s create response returns
        // `trigger_at` as a top-level convenience field (sibling to `id`,
        // `full_id`), not nested under `"properties"`. The pre-existing
        // `inside_properties` guard alone did not protect it, so Agent-mode
        // compaction rewrote it: `at` here is far outside the 24h relative
        // window, so pre-fix it would have been minute-truncated to
        // "2026-07-11T19:00", discarding the seconds and the "-04:00"
        // offset the caller needs to round-trip the exact value verbatim.
        let at = "2026-07-11T19:00:00-04:00";
        let v = json!({
            "id": "a1b2c3d4",
            "full_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
            "event_type": "remind",
            "trigger_at": at,
            "repeat": null,
            "status": "pending",
        });
        let out = agent(v);
        assert_eq!(out["trigger_at"], json!(at));
    }

    #[test]
    fn agent_does_not_compact_top_level_trigger_at_utc() {
        let at = "2026-07-11T23:00:00Z";
        let v = json!({"trigger_at": at});
        let out = agent(v);
        assert_eq!(out["trigger_at"], json!(at));
    }

    #[test]
    fn agent_does_not_compact_top_level_trigger_at_offset_less() {
        let at = "2026-07-11T23:00:00";
        let v = json!({"trigger_at": at});
        let out = agent(v);
        assert_eq!(out["trigger_at"], json!(at));
    }

    #[test]
    fn agent_still_renders_other_top_level_timestamps_alongside_trigger_at() {
        // The `trigger_at` exemption is scoped to that field name only — a
        // sibling generic timestamp field still converts to exact UTC.
        let v = json!({
            "trigger_at": "2026-07-11T19:00:00-04:00",
            "created_at": "2020-01-01T10:30:45.123456Z",
        });
        let out = agent(v);
        assert_eq!(out["trigger_at"], json!("2026-07-11T19:00:00-04:00"));
        assert_eq!(out["created_at"], json!("2020-01-01T10:30:45.123456Z"));
    }

    #[test]
    fn agent_does_not_compact_top_level_due() {
        // gtd.assign/gtd.tasks/gtd.next return the caller-supplied `due` as
        // a top-level convenience field mirroring `properties.due`; it must
        // round-trip verbatim through Agent-mode presentation, the same
        // guarantee already given to `trigger_at`.
        let due = "2026-08-01T09:30:15-04:00";
        let v = json!({"due": due});
        let out = agent(v);
        assert_eq!(out["due"], json!(due));
    }

    #[test]
    fn agent_still_protects_nested_trigger_at_under_properties() {
        // Pre-existing protection (agenda/get responses nest trigger_at
        // under "properties") must remain intact alongside the new
        // top-level, field-name-based guard.
        let at = "2026-07-11T19:00:00-04:00";
        let v = json!({
            "id": "a1b2c3d4",
            "properties": {"trigger_at": at, "status": "pending"},
        });
        let out = agent(v);
        assert_eq!(out["properties"]["trigger_at"], json!(at));
    }

    #[test]
    fn agent_recurses_into_nested_objects() {
        let v = json!({
            "items": [
                {
                    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
                    "tags": [],
                    "score": 0.9999
                }
            ]
        });
        let out = agent(v);
        let item = &out["items"][0];
        assert_eq!(item["id"], json!("a1b2c3d4"));
        assert!(item.get("tags").is_none());
        let s = item["score"].as_f64().unwrap();
        assert!((s - 1.0).abs() < 1e-9);
    }

    // full_id must never be shortened in Agent mode: it's the caller's
    // stable chaining handle.
    #[test]
    fn agent_preserves_full_id_as_36_chars() {
        let uuid = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
        let v = json!({"id": uuid, "full_id": uuid, "title": "X"});
        let out = agent(v);
        // `id` is shortened to 8 chars
        assert_eq!(
            out["id"],
            json!("a1b2c3d4"),
            "id should be 8-char short form"
        );
        // `full_id` must remain the full 36-char UUID
        assert_eq!(
            out["full_id"].as_str().unwrap().len(),
            36,
            "full_id must be 36 chars in agent mode"
        );
        assert_eq!(
            out["full_id"],
            json!(uuid),
            "full_id must equal the original UUID"
        );
        // Verify the invariant: full_id starts with the short id prefix
        assert!(
            out["full_id"]
                .as_str()
                .unwrap()
                .starts_with(out["id"].as_str().unwrap()),
            "full_id must start with the short id prefix"
        );
    }

    #[test]
    fn is_canonical_uuid_recognizes_valid() {
        assert!(is_canonical_uuid("a1b2c3d4-e5f6-7890-abcd-ef1234567890"));
        assert!(!is_canonical_uuid("a1b2c3d4"));
        assert!(!is_canonical_uuid("not-a-uuid-at-all-here---------"));
    }

    #[test]
    fn looks_like_iso8601_recognizes_valid() {
        assert!(looks_like_iso8601("2026-05-23T16:18:15.234567Z"));
        assert!(!looks_like_iso8601("not a timestamp"));
        assert!(!looks_like_iso8601("2026-05-23"));
    }

    /// Format Unix seconds as ISO-8601 for test construction.
    fn unix_to_iso8601(unix: i64) -> String {
        let (y, mo, d, h, mi, s) = unix_to_civil(unix);
        format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{s:02}Z")
    }

    fn unix_to_civil(unix: i64) -> (i64, i64, i64, i64, i64, i64) {
        let s = unix % 86400;
        let days = unix / 86400;
        let h = s / 3600;
        let m = (s % 3600) / 60;
        let sec = s % 60;
        // Howard Hinnant civil_from_days
        let z = days + 719468;
        let era = z.div_euclid(146097);
        let doe = z - era * 146097;
        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
        let y = yoe + era * 400;
        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
        let mp = (5 * doy + 2) / 153;
        let d = doy - (153 * mp + 2) / 5 + 1;
        let mo = if mp < 10 { mp + 3 } else { mp - 9 };
        let y = if mo <= 2 { y + 1 } else { y };
        (y, mo, d, h, m, sec)
    }

    #[test]
    fn agent_does_not_shorten_uuid_shaped_content_fields() {
        let uuid = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
        let out = agent(json!({
            "id": uuid,
            "full_id": uuid,
            "content": uuid,
            "description": uuid,
            "title": uuid,
            "query": uuid,
        }));

        assert_eq!(out["id"], json!("a1b2c3d4"));
        assert_eq!(out["full_id"], json!(uuid));
        assert_eq!(out["content"], json!(uuid));
        assert_eq!(out["description"], json!(uuid));
        assert_eq!(out["title"], json!(uuid));
        assert_eq!(out["query"], json!(uuid));
    }

    #[test]
    fn agent_shortens_suffix_id_fields() {
        let uuid = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
        let out = agent(json!({
            "note_id": uuid,
            "source_id": uuid,
            "target_id": uuid,
        }));

        assert_eq!(out["note_id"], json!("a1b2c3d4"));
        assert_eq!(out["source_id"], json!("a1b2c3d4"));
        assert_eq!(out["target_id"], json!("a1b2c3d4"));
    }

    #[test]
    fn agent_preserves_strict_round_trip_uuid_fields() {
        let uuid = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
        let out = agent(json!({
            "context_entity_id": uuid,
            "thread_id": uuid,
            "session_id": uuid,
            "project_id": uuid,
            "properties": {
                "context_entity_id": uuid,
                "thread_id": uuid,
                "outbound_ref": uuid,
                "parent_id": uuid,
                "session_id": uuid,
                "project_id": uuid,
            },
            "parent_id": uuid,
        }));

        assert_eq!(out["context_entity_id"], json!(uuid));
        assert_eq!(out["thread_id"], json!(uuid));
        assert_eq!(out["session_id"], json!(uuid));
        assert_eq!(out["project_id"], json!(uuid));
        assert_eq!(out["properties"]["context_entity_id"], json!(uuid));
        assert_eq!(out["properties"]["thread_id"], json!(uuid));
        assert_eq!(out["properties"]["outbound_ref"], json!(uuid));
        assert_eq!(out["properties"]["parent_id"], json!(uuid));
        assert_eq!(out["properties"]["session_id"], json!(uuid));
        assert_eq!(out["properties"]["project_id"], json!(uuid));
        assert_eq!(out["parent_id"], json!(uuid));
    }

    // ── ADR-078: OutputFormat tests ───────────────────────────────────────────

    /// (a) verbose json preserves full shape (no field dropped, no transformation).
    #[test]
    fn format_verbose_json_preserves_full_shape() {
        let v = json!({
            "full_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
            "namespace": "local",
            "properties": {"k": "v"},
            "title": "test"
        });
        let rendered = render_format(v.clone(), OutputFormat::Json, PresentationMode::Verbose);
        let parsed: Value = serde_json::from_str(&rendered).unwrap();
        // full_id must not be dropped in json mode.
        assert!(
            parsed.get("full_id").is_some(),
            "json mode must keep full_id"
        );
        // namespace must NOT be elided in json mode.
        assert_eq!(
            parsed.get("namespace").and_then(Value::as_str),
            Some("local")
        );
        // properties must NOT be deduped in json mode.
        assert!(parsed.get("properties").is_some());
    }

    /// (a-agent-json) Agent JSON applies the Machine-scope redundancy
    /// reduction: `namespace`/duplicate-`properties` elision, but `full_id`
    /// is retained — it is the caller's chaining handle, not a view drop
    /// (ADR-078 Amendment 3, corrected).
    #[test]
    fn format_agent_json_drops_redundancy() {
        let v = json!({
            "full_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
            "namespace": "local",
            "title": "test",
            "status": "next",
            "properties": {"status": "next", "additive": true}
        });
        let rendered = render_format(v, OutputFormat::Json, PresentationMode::Agent);
        let parsed: Value = serde_json::from_str(&rendered).unwrap();
        assert!(
            parsed.get("full_id").is_some(),
            "Agent JSON must keep full_id: it is the machine contract's chaining handle"
        );
        assert!(parsed.get("namespace").is_none());
        assert_eq!(parsed["status"], json!("next"));
        assert!(parsed["properties"].get("status").is_none());
        assert_eq!(parsed["properties"]["additive"], json!(true));
    }

    /// Agent JSON (Machine scope) keeps `full_id` while dropping
    /// `namespace="local"` and duplicate `properties`; Auto (View scope) on
    /// the same record still drops all three — the view scope is unchanged
    /// by Amendment 3's correction.
    #[test]
    fn agent_json_keeps_full_id_while_auto_still_drops_it() {
        let v = json!({
            "full_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
            "namespace": "local",
            "title": "test",
            "properties": {"title": "test", "additive": true}
        });

        let json_rendered = render_format(v.clone(), OutputFormat::Json, PresentationMode::Agent);
        let json_parsed: Value = serde_json::from_str(&json_rendered).unwrap();
        assert!(
            json_parsed.get("full_id").is_some(),
            "Agent JSON must keep full_id"
        );
        assert!(
            json_parsed.get("namespace").is_none(),
            "Agent JSON must elide namespace=\"local\""
        );
        assert!(
            json_parsed["properties"].get("title").is_none(),
            "Agent JSON must dedupe a duplicate properties entry"
        );
        assert_eq!(json_parsed["properties"]["additive"], json!(true));

        let auto_rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
        assert!(
            !auto_rendered.contains("full_id"),
            "Auto (view scope) must still drop full_id: {auto_rendered}"
        );
        assert!(
            !auto_rendered.contains("\"namespace\""),
            "Auto must still elide namespace=\"local\": {auto_rendered}"
        );
    }

    /// (b1) homogeneous record array → markdown table with header + separator + rows.
    #[test]
    fn format_auto_homogeneous_array_renders_markdown_table() {
        let v = json!([
            {"id": "abc", "title": "First"},
            {"id": "def", "title": "Second"}
        ]);
        let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
        assert!(rendered.starts_with('|'), "must start with |");
        assert!(
            rendered.contains("| id |") || rendered.contains("| id"),
            "must have id column"
        );
        assert!(rendered.contains("title"), "must have title column");
        assert!(rendered.contains("|---|"), "must have separator row");
        assert!(rendered.contains("abc"), "must have first row data");
        assert!(rendered.contains("Second"), "must have second row data");
    }

    /// (b2) single record → compact JSON, lossless (kv-block renderer removed).
    #[test]
    fn format_auto_single_record_renders_compact_json() {
        let v = json!({"id": "abc", "title": "Hello World"});
        let rendered = render_format(v.clone(), OutputFormat::Auto, PresentationMode::Agent);
        let parsed: Value = serde_json::from_str(&rendered).expect("must be valid JSON");
        assert_eq!(parsed, v, "single record must round-trip losslessly");
        assert!(
            !rendered.starts_with('|'),
            "single record must not be a markdown table"
        );
    }

    /// (b2-lossless) a single record with a large payload field (a compose
    /// briefing's `markdown`) arrives whole — the former kv-block renderer
    /// truncated it.
    #[test]
    fn format_auto_single_record_large_payload_survives_whole() {
        let briefing = "line one\nline two\n".repeat(500); // ~9KB, newlines included
        let v = json!({"id": "abc", "markdown": briefing.clone()});
        let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
        let parsed: Value = serde_json::from_str(&rendered).expect("must be valid JSON");
        assert_eq!(
            parsed.get("markdown").and_then(Value::as_str),
            Some(briefing.as_str()),
            "large payload field must survive untruncated"
        );
    }

    /// Envelope siblings survive table rendering: a `query`-style page whose
    /// `has_more` is dropped reads as complete — fail-open.
    #[test]
    fn format_auto_table_preserves_sibling_scalars() {
        let v = json!({
            "results": [
                {"id": "abc", "title": "First"},
                {"id": "def", "title": "Second"}
            ],
            "has_more": true,
            "offset": 20,
            "page_size": 2,
            "truncated": false
        });
        let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
        assert!(rendered.contains("| id"), "records must render as a table");
        assert!(
            rendered.contains("has_more: true"),
            "has_more sibling must survive: {rendered}"
        );
        assert!(
            rendered.contains("offset: 20"),
            "offset sibling must survive"
        );
        assert!(
            rendered.contains("page_size: 2"),
            "page_size sibling must survive"
        );
        assert!(
            rendered.contains("truncated: false"),
            "truncated sibling must survive"
        );
    }

    /// Nested table cells render a constant elision marker, never
    /// truncated pseudo-JSON that reads as data while missing fields.
    #[test]
    fn format_auto_nested_cell_renders_elision_marker() {
        let big_nested: Value = json!({"k": "v".repeat(300), "other": {"deep": true}});
        let v = json!([
            {"id": "abc", "properties": big_nested},
            {"id": "def", "properties": {"x": 1}}
        ]);
        let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
        assert!(
            rendered.contains("{…}"),
            "nested object cell must render the elision marker: {rendered}"
        );
        assert!(
            !rendered.contains("..."),
            "no truncated pseudo-JSON in nested cells"
        );
    }

    /// Arrays of scalars (tags) still render as compact JSON in cells.
    #[test]
    fn format_auto_scalar_array_cell_renders_compact_json() {
        let v = json!([
            {"id": "abc", "tags": ["lesson", "khive"]},
            {"id": "def", "tags": ["adr"]}
        ]);
        let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
        assert!(
            rendered.contains(r#"["lesson","khive"]"#),
            "scalar array cell must be compact JSON: {rendered}"
        );
    }

    /// Identity/decision columns are exempt from truncation: a truncated
    /// title cannot be selected on, a truncated signature is unusable.
    #[test]
    fn format_auto_identity_columns_not_truncated() {
        let long_title = "T".repeat(300);
        let long_note = "N".repeat(300);
        let v = json!([
            {"id": "abc", "title": long_title.clone(), "note": long_note.clone()},
            {"id": "def", "title": "short", "note": "short"}
        ]);
        let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
        assert!(
            rendered.contains(&long_title),
            "title column must not be truncated"
        );
        assert!(
            !rendered.contains(&long_note),
            "non-exempt column must still truncate"
        );
    }

    /// Verbose presentation disables cell truncation entirely (ADR-078 §3a).
    #[test]
    fn format_auto_verbose_disables_truncation() {
        let long_note = "N".repeat(300);
        let v = json!([
            {"id": "abc", "note": long_note.clone()},
            {"id": "def", "note": "short"}
        ]);
        let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Verbose);
        assert!(
            rendered.contains(&long_note),
            "verbose must render full cell content"
        );
    }

    /// The pre-pass hoists named scalar payload fields (`trigger_at`, `due`,
    /// `status`) out of `properties` so they can surface as table columns —
    /// a scheduled event carries them only inside `properties`.
    #[test]
    fn table_path_hoists_payload_scalars_to_columns() {
        // The hoist is table-path only (ADR-078 Amendment 2): two scheduled
        // events whose trigger_at/status live inside `properties` must gain
        // top-level columns in the rendered table.
        let record = |n: u32| {
            json!({
                "id": format!("evt-{n}"),
                "properties": {
                    "trigger_at": "2026-09-01T14:00:00-04:00",
                    "status": "pending",
                    "dispatch_receipt": {"state": "succeeded"}
                }
            })
        };
        let out = render_format(
            json!([record(1), record(2)]),
            OutputFormat::Auto,
            PresentationMode::Agent,
        );
        let header = out.lines().next().expect("table header");
        assert!(
            header.contains("trigger_at") && header.contains("status"),
            "hoisted scalars must appear as table columns, got header: {header}"
        );
        assert!(
            out.contains("2026-09-01T14:00:00-04:00") && out.contains("pending"),
            "hoisted values must render in cells:\n{out}"
        );
    }

    #[test]
    fn redundancy_drop_no_longer_hoists_outside_tables() {
        // Rule-separating control for the table-scoped hoist: the §7 pre-pass
        // alone must leave the properties bag in place, so a single record's
        // compact-JSON fallback keeps its shape.
        let v = json!({
            "id": "abc",
            "properties": {
                "trigger_at": "2026-09-01T14:00:00-04:00",
                "status": "pending"
            }
        });
        let reduced = apply_redundancy_drop(v, RedundancyScope::View);
        assert!(
            reduced.get("trigger_at").is_none() && reduced.get("status").is_none(),
            "the pre-pass must not hoist; the hoist is table-path only"
        );
        let props = reduced.get("properties").expect("properties must remain");
        assert_eq!(
            props.get("status").and_then(Value::as_str),
            Some("pending"),
            "fallback shape keeps payload fields inside properties"
        );
    }

    #[test]
    fn sibling_string_with_newline_renders_as_json_literal() {
        // Escaping contract: a newline-bearing sibling string must not be able
        // to fabricate an additional `key: value` line.
        let v = json!({
            "items": [{"id": "a", "kind": "x"}, {"id": "b", "kind": "y"}],
            "note": "line one\nforged_key: forged_value",
            "has_more": true
        });
        let out = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
        assert!(
            !out.contains("\nforged_key: forged_value"),
            "raw newline from a sibling string must not start a new line:\n{out}"
        );
        assert!(
            out.contains(r#"note: "line one\nforged_key: forged_value""#),
            "newline-bearing sibling renders as its JSON literal:\n{out}"
        );
        assert!(out.contains("has_more: true"), "siblings still preserved");
    }

    #[test]
    fn carriage_return_in_cell_collapses_like_newline() {
        // Escaping contract pin: cells collapse \r exactly like \n, so a
        // \r- or \r\n-bearing value cannot smuggle a raw line break into
        // the table body and forge row structure.
        let v = json!([
            {"id": "a", "note": "before\rafter"},
            {"id": "b", "note": "one\r\ntwo"}
        ]);
        let out = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
        assert!(
            !out.contains('\r'),
            "no raw carriage return may survive into rendered output:\n{out:?}"
        );
        assert!(
            out.contains("before after") && out.contains("one  two"),
            "\\r and \\r\\n collapse to spaces inside cells:\n{out}"
        );
    }

    /// The hoist never overwrites an existing top-level sibling.
    #[test]
    fn redundancy_drop_hoist_does_not_overwrite_top_level() {
        let v = json!({
            "id": "abc",
            "status": "active",
            "properties": {"status": "pending"}
        });
        let reduced = apply_redundancy_drop(v, RedundancyScope::View);
        assert_eq!(
            reduced.get("status").and_then(Value::as_str),
            Some("active"),
            "existing top-level status must win"
        );
        assert_eq!(
            reduced
                .get("properties")
                .and_then(|p| p.get("status"))
                .and_then(Value::as_str),
            Some("pending"),
            "conflicting properties value must stay where it was"
        );
    }

    /// (b3) fallback: auto on heterogeneous/scalar value falls back to compact json.
    #[test]
    fn format_auto_scalar_fallback_compact_json() {
        let v = json!(42);
        let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
        assert_eq!(rendered, "42");
    }

    /// (c) table format forces markdown table even when shape would normally be kv.
    #[test]
    fn format_table_forces_markdown_when_array() {
        let v = json!({
            "items": [
                {"name": "A", "score": 1},
                {"name": "B", "score": 2}
            ]
        });
        let rendered = render_format(v, OutputFormat::Table, PresentationMode::Agent);
        assert!(
            rendered.contains("|"),
            "table format must produce markdown table"
        );
        assert!(rendered.contains("name"), "must have name column");
        assert!(rendered.contains("score"), "must have score column");
    }

    /// (c-fallback) table format falls back to compact json when no record array found.
    #[test]
    fn format_table_falls_back_to_json_when_no_array() {
        let v = json!({"single": "value"});
        let rendered = render_format(v, OutputFormat::Table, PresentationMode::Agent);
        // No record array → compact JSON fallback.
        let parsed: Value = serde_json::from_str(&rendered).unwrap();
        assert_eq!(parsed["single"], json!("value"));
    }

    /// (d) redundancy-drop: auto/table skipped in Verbose mode (§7).
    #[test]
    fn format_auto_verbose_skips_redundancy_drop() {
        let v = json!({
            "full_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
            "namespace": "local",
            "title": "test"
        });
        // In Verbose mode, redundancy drop must be skipped.
        // The value is a single object → compact JSON; full_id and namespace stay.
        let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Verbose);
        assert!(
            rendered.contains("full_id"),
            "verbose must preserve full_id"
        );
        assert!(
            rendered.contains("namespace"),
            "verbose must preserve namespace"
        );
    }

    /// Indirect check that the redundancy pre-pass doesn't corrupt an error
    /// envelope's shape; the actual ok=false bypass is enforced by
    /// `render_result`, not by this pre-pass.
    #[test]
    fn redundancy_drop_does_not_corrupt_error_shape() {
        let v = json!({"ok": false, "error": "something failed", "namespace": "local"});
        // apply_redundancy_drop is a pure value transform with no knowledge of
        // `ok`: bypassing it for error envelopes is the caller's job
        // (render_result in server.rs). This only checks the pre-pass itself
        // doesn't lose the error field.
        let reduced = apply_redundancy_drop(v.clone(), RedundancyScope::View);
        assert!(
            reduced.get("error").is_some(),
            "redundancy drop must preserve error field"
        );
        assert_eq!(
            reduced.get("ok").and_then(Value::as_bool),
            Some(false),
            "redundancy drop must preserve ok=false"
        );
    }

    /// Properties dedup removes only keys that match a top-level sibling exactly.
    #[test]
    fn redundancy_drop_properties_dedup() {
        let v = json!({
            "id": "abc",
            "title": "Same",
            "properties": {
                "title": "Same",  // duplicate → removed
                "extra": "unique" // not at top level → kept
            }
        });
        let reduced = apply_redundancy_drop(v, RedundancyScope::View);
        let props = reduced.get("properties").expect("properties must remain");
        assert!(props.get("extra").is_some(), "unique property must be kept");
        assert!(
            props.get("title").is_none(),
            "duplicate top-level property must be removed"
        );
    }

    /// Cell truncation: text > 120 chars gets `...` appended.
    #[test]
    fn cell_text_truncates_long_values() {
        let long = "X".repeat(200);
        let v = json!([
            {"col": long.clone()},
            {"col": "short"}
        ]);
        let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
        // Cell must be truncated to ~120 chars + "..."
        assert!(
            rendered.contains("..."),
            "long cell must be truncated with ..."
        );
        assert!(
            !rendered.contains(&long),
            "full long string must not appear in table"
        );
    }

    /// Cell truncation must not panic on multi-byte UTF-8 characters.
    ///
    /// A string of 119 ASCII bytes followed by a 3-byte CJK character and more
    /// text has `len() > 120` but byte index 120 falls inside the CJK char.
    /// The old byte-slice truncation would panic; char-boundary truncation is safe.
    #[test]
    fn cell_text_truncation_is_utf8_safe() {
        // 119 ASCII 'a' bytes, then CJK char U+4E2D (3 bytes each), then more text.
        // Total byte length: 119 + 3 * 10 + 5 > 120, but byte 120 is inside a CJK char.
        let prefix = "a".repeat(119);
        let suffix = "中".repeat(10); // each '中' is 3 bytes
        let long_multibyte = format!("{prefix}{suffix}trailing");
        let v = json!([
            {"col": long_multibyte.clone()},
            {"col": "ok"}
        ]);
        // Must not panic — this was the bug.
        let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
        assert!(
            rendered.contains("..."),
            "multibyte cell must be truncated with ..."
        );
        // The rendered string must be valid UTF-8 (no partial char slicing).
        assert!(
            std::str::from_utf8(rendered.as_bytes()).is_ok(),
            "rendered output must be valid UTF-8"
        );
    }

    // --- parse_iso8601_unix / relative-time offset handling ---

    #[test]
    fn parse_iso8601_unix_negative_offset_matches_equivalent_utc() {
        // "-04:00" is 4 hours behind UTC, so 11:55 local == 15:55Z.
        assert_eq!(
            parse_iso8601_unix("2026-07-09T11:55:00-04:00"),
            parse_iso8601_unix("2026-07-09T15:55:00Z")
        );
    }

    #[test]
    fn parse_iso8601_unix_positive_offset_matches_equivalent_utc() {
        // "+04:00" is 4 hours ahead of UTC, so 20:15 local == 16:15Z.
        assert_eq!(
            parse_iso8601_unix("2026-05-23T20:15:00+04:00"),
            parse_iso8601_unix("2026-05-23T16:15:00Z")
        );
    }

    #[test]
    fn parse_iso8601_unix_zero_offset_matches_z() {
        assert_eq!(
            parse_iso8601_unix("2026-07-09T15:55:00+00:00"),
            parse_iso8601_unix("2026-07-09T15:55:00Z")
        );
    }

    #[test]
    fn parse_iso8601_unix_compact_offset_form_matches_colon_form() {
        assert_eq!(
            parse_iso8601_unix("2026-07-09T11:55:00-0400"),
            parse_iso8601_unix("2026-07-09T11:55:00-04:00")
        );
    }

    #[test]
    fn parse_iso8601_unix_fractional_seconds_with_offset() {
        // Fractional seconds are dropped (whole-second precision only) but
        // must not prevent the trailing offset from being applied.
        assert_eq!(
            parse_iso8601_unix("2026-07-09T11:55:00.123-04:00"),
            parse_iso8601_unix("2026-07-09T15:55:00Z")
        );
    }

    #[test]
    fn parse_iso8601_unix_fractional_seconds_with_z() {
        assert_eq!(
            parse_iso8601_unix("2026-07-09T15:55:00.999Z"),
            parse_iso8601_unix("2026-07-09T15:55:00Z")
        );
    }

    #[test]
    fn parse_iso8601_unix_rejects_bare_form() {
        assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00"), None);
    }

    #[test]
    fn parse_iso8601_unix_malformed_tail_returns_none() {
        assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00X"), None);
        assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00+04"), None);
        assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00."), None);
    }

    #[test]
    fn parse_iso8601_unix_out_of_range_offset_returns_none() {
        // Hour out of range (>23), colon and compact forms.
        assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00+24:00"), None);
        assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00+2400"), None);
        // Minute out of range (>59), colon and compact forms.
        assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00+01:60"), None);
        assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00+0160"), None);
    }

    #[test]
    fn parse_iso8601_unix_max_valid_offset_boundary_is_accepted() {
        // +23:59 / -23:59 are the largest valid offsets and must still parse.
        assert!(parse_iso8601_unix("2026-07-09T15:55:00+23:59").is_some());
        assert!(parse_iso8601_unix("2026-07-09T15:55:00-23:59").is_some());
        assert!(parse_iso8601_unix("2026-07-09T15:55:00+2359").is_some());
    }

    #[test]
    fn exact_timestamp_converts_future_offset_without_relative_form() {
        let out = exact_timestamp("2025-05-23T16:08:00-02:00").unwrap();
        assert_eq!(out.0, "2025-05-23T18:08:00Z");
        assert!(out.1 > NOW);
    }

    #[test]
    fn exact_timestamp_converts_past_offset_and_retains_fraction() {
        let out = exact_timestamp("2025-05-23T20:05:00.123+04:00").unwrap();
        assert_eq!(out.0, "2025-05-23T16:05:00.123Z");
        assert_eq!(out.1, NOW - 180);
    }
}

#[cfg(test)]
mod stream_presentation_tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn stream_agent_json_preserves_opaque_record_and_empty_page() {
        let record = json!([{"id": "aabbccdd-1234-4321-1234-abcdefabcdef", "score": 0.123456789, "created_at": "2026-09-08T00:00:00.123456Z", "empty": [], "null": null, "namespace": "local", "properties": {"namespace": "local"}}]);
        for payload in [record, Value::Null, json!([]), json!({}), json!("")] {
            let page = json!({"entries": [{"seq": 1, "id": "aabbccdd-1234-4321-1234-abcdefabcdef", "created_at": "2026-09-08T00:00:00.123456Z", "record": payload}], "head_seq": 1, "next_after": null});
            let presented = present(page, PresentationMode::Agent, 0);
            let out = prepare_format_value(presented, OutputFormat::Json, PresentationMode::Agent);
            assert_eq!(out["entries"][0].get("record"), Some(&payload));
            assert!(out.get("next_after").is_some_and(Value::is_null));
        }
        let empty = json!({"entries": [], "head_seq": 0, "next_after": null});
        assert_eq!(present(empty.clone(), PresentationMode::Agent, 0), empty);
    }
}

#[cfg(test)]
mod issue_2537_standard_tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn issue_2537_standard_context_baseline_controls() {
        let timestamp = "2026-01-01T00:00:00.123456Z";
        let now = 1_767_225_780; // 2026-01-01T00:03:00Z, independently literal clock.
        let uuid = "aabbccdd-1234-4321-1234-abcdefabcdef";
        let payload = json!({"id":uuid,"created_at":timestamp,"empty":[],"null":null});
        let value = json!({"tool":"stream.batch","policy":"StreamBatchReceipts","id":uuid,
            "updated_at":timestamp,"score":0.123456,"empty":[],"null":null,
            "results":[{"id":uuid,"version":1,"updated_at":timestamp,"details":{"updated_at":timestamp}}],
            "properties":{"created_at":timestamp,"id":uuid,"empty":""},"trigger_at":timestamp,"due":timestamp,
            "entry":{"seq":1,"id":uuid,"created_at":timestamp,"record":payload},
            "cursor":{"head_seq":0,"entries":[],"next_after":null}});
        let shown = present(value.clone(), PresentationMode::Agent, now);
        assert_eq!(shown["updated_at"], timestamp);
        assert_eq!(shown["results"][0]["updated_at"], timestamp);
        assert_eq!(shown["results"][0]["details"]["updated_at"], timestamp);
        assert_eq!(shown["id"], "aabbccdd");
        assert_eq!(shown["score"], json!(0.123));
        assert!(shown.get("empty").is_none());
        assert!(shown.get("null").is_none());
        assert_eq!(
            shown["properties"],
            json!({"created_at":timestamp,"id":"aabbccdd","empty":""})
        );
        assert_eq!(shown["trigger_at"], timestamp);
        assert_eq!(shown["due"], timestamp);
        assert_eq!(shown["entry"]["record"], payload);
        assert_eq!(shown["entry"]["created_at"], timestamp);
        assert_eq!(shown["cursor"], value["cursor"]);
        for mode in [PresentationMode::Verbose, PresentationMode::Human] {
            assert_eq!(present(value.clone(), mode, now), value);
        }
        assert_eq!(
            present(
                json!({"properties":timestamp}),
                PresentationMode::Agent,
                now
            )["properties"],
            timestamp
        );
        assert_eq!(
            present(
                json!({"properties":[timestamp,{"created_at":timestamp}]}),
                PresentationMode::Agent,
                now
            )["properties"],
            json!([timestamp,{"created_at":timestamp}])
        );
    }
}

#[cfg(test)]
mod issue_2537_receipt_policy_tests {
    use super::*;
    use serde_json::json;

    const TIMESTAMP: &str = "2026-01-01T00:00:00.123456Z";
    const NOW: i64 = 1_767_225_780;
    const UUID: &str = "aabbccdd-1234-4321-1234-abcdefabcdef";

    #[test]
    fn issue_2537_receipt_policies_preserve_only_the_named_fields() {
        let append = json!({
            "id": UUID, "created_at": TIMESTAMP, "updated_at": TIMESTAMP,
            "score": 0.123456, "empty": [], "null": null,
            "details": {"created_at": TIMESTAMP},
            "ticker": {"last_tick_at": TIMESTAMP},
        });
        let batch = json!({
            "id": UUID, "created_at": TIMESTAMP, "updated_at": TIMESTAMP,
            "results": [{
                "id": UUID, "created_at": TIMESTAMP, "updated_at": TIMESTAMP,
                "details": {"created_at": TIMESTAMP, "updated_at": TIMESTAMP},
                "record": {"updated_at": TIMESTAMP},
                "score": 0.123456, "empty": [], "null": null,
            }],
            "properties": {"created_at": TIMESTAMP, "id": UUID, "empty": ""},
            "entry": {"seq": 1, "id": UUID, "created_at": TIMESTAMP,
                "record": {"id": UUID, "updated_at": TIMESTAMP, "empty": [], "null": null}},
            "trigger_at": TIMESTAMP, "due": TIMESTAMP,
            "ticker": {"last_tick_at": TIMESTAMP},
        });
        for (value, policy) in [
            (append, VerbPresentationPolicy::StreamAppendReceipt),
            (batch, VerbPresentationPolicy::StreamBatchReceipts),
        ] {
            let mut expected = present(value.clone(), PresentationMode::Agent, NOW);
            assert_eq!(expected["created_at"], TIMESTAMP);
            assert_eq!(expected["updated_at"], TIMESTAMP);
            assert_eq!(expected["id"], "aabbccdd");
            assert_eq!(expected["ticker"]["last_tick_at"], TIMESTAMP);
            if policy == VerbPresentationPolicy::StreamAppendReceipt {
                expected["created_at"] = json!(TIMESTAMP);
            } else {
                expected["results"][0]["created_at"] = json!(TIMESTAMP);
                expected["results"][0]["updated_at"] = json!(TIMESTAMP);
                expected["results"][0]
                    .as_object_mut()
                    .unwrap()
                    .remove("created_at_relative");
            }
            assert_eq!(
                present_with_policy(value.clone(), PresentationMode::Agent, NOW, policy),
                expected
            );
            for mode in [PresentationMode::Verbose, PresentationMode::Human] {
                assert_eq!(present_with_policy(value.clone(), mode, NOW, policy), value);
            }
            assert_eq!(
                present_with_policy(
                    value.clone(),
                    PresentationMode::Agent,
                    NOW,
                    VerbPresentationPolicy::AlwaysVerbose
                ),
                value
            );
        }
    }

    #[test]
    fn issue_2537_receipt_paths_do_not_match_other_containers_or_descendants() {
        let row = json!({"created_at": TIMESTAMP, "updated_at": TIMESTAMP});
        for (policy, cases) in [
            (
                VerbPresentationPolicy::StreamAppendReceipt,
                vec![
                    json!([row.clone()]),
                    json!({"details": row.clone()}),
                    json!({"results": [row.clone()]}),
                    json!({"created_at": {"created_at": TIMESTAMP}}),
                ],
            ),
            (
                VerbPresentationPolicy::StreamBatchReceipts,
                vec![
                    json!([{"results": [row.clone()]}]),
                    json!({"results": row.clone()}),
                    json!({"results": [[row.clone()]]}),
                    json!({"details": {"results": [row.clone()]}}),
                    json!({"results": [{"details": row.clone(), "record": row.clone(), "results": [row.clone()]}]}),
                    json!({"results": [{"created_at": {"updated_at": TIMESTAMP}, "updated_at": null}]}),
                ],
            ),
        ] {
            for value in cases {
                assert_eq!(
                    present_with_policy(value.clone(), PresentationMode::Agent, NOW, policy),
                    present(value.clone(), PresentationMode::Agent, NOW),
                    "container must not acquire receipt protection: {value}"
                );
            }
        }
    }

    #[test]
    fn issue_2537_receipt_strings_are_preserved_without_parsing() {
        for text in ["", "not a timestamp", "2026-01-01T05:30:00.123456+05:30"] {
            let append = json!({"created_at": text});
            assert_eq!(
                present_with_policy(
                    append.clone(),
                    PresentationMode::Agent,
                    NOW,
                    VerbPresentationPolicy::StreamAppendReceipt
                ),
                append
            );
            let batch = json!({"results": [{"created_at": text, "updated_at": text}]});
            assert_eq!(
                present_with_policy(
                    batch.clone(),
                    PresentationMode::Agent,
                    NOW,
                    VerbPresentationPolicy::StreamBatchReceipts
                ),
                batch
            );
        }
        for non_string in [Value::Null, json!([]), json!({}), json!(42), json!(true)] {
            for (value, policy) in [
                (
                    json!({"created_at": non_string}),
                    VerbPresentationPolicy::StreamAppendReceipt,
                ),
                (
                    json!({"results": [{"created_at": non_string, "updated_at": non_string}]}),
                    VerbPresentationPolicy::StreamBatchReceipts,
                ),
            ] {
                assert_eq!(
                    present_with_policy(value.clone(), PresentationMode::Agent, NOW, policy),
                    present(value, PresentationMode::Agent, NOW)
                );
            }
        }
    }
}

#[cfg(test)]
mod parsed_note_content_tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn issue2757_content_is_opaque_to_metadata_and_format_reductions() {
        let payload = json!([
            {"id":"11111111-1111-4111-8111-111111111111", "full_id":"keep", "namespace":"local",
             "created_at":"2026-09-15T12:34:56.123456Z", "score":0.123456789,
             "nil":null, "empty":"", "array":[], "object":{},
             "properties":{"id":"11111111-1111-4111-8111-111111111111"}},
            {"status":"pending"}
        ]);
        for (scope, response, pointer) in [
            (
                NoteContentScope::Record,
                json!({"id":"22222222-2222-4222-8222-222222222222", "content":payload}),
                "/content",
            ),
            (
                NoteContentScope::Items,
                json!({"items":[{"id":"22222222-2222-4222-8222-222222222222", "content":payload}], "requested_limit":1, "effective_limit":1, "limit_clamped":false}),
                "/items/0/content",
            ),
            (
                NoteContentScope::Notes,
                json!({"notes":[{"id":"22222222-2222-4222-8222-222222222222", "content":payload}], "next_after":null}),
                "/notes/0/content",
            ),
        ] {
            let presented =
                scope.protect(response, |value| present(value, PresentationMode::Agent, 0));
            for format in [OutputFormat::Json, OutputFormat::Auto, OutputFormat::Table] {
                let rendered = render_format_with_note_content(
                    presented.clone(),
                    format,
                    PresentationMode::Agent,
                    scope,
                );
                let actual: Value = serde_json::from_str(&rendered)
                    .expect("single note stays a JSON record, never a table of its body");
                let expected = if format == OutputFormat::Table {
                    Value::String(payload.to_string())
                } else {
                    payload.clone()
                };
                assert_eq!(actual.pointer(pointer), Some(&expected));
            }
        }
    }
}

#[cfg(test)]
mod adr045_amendment9_tests {
    use super::*;
    use serde_json::json;

    const NOW: i64 = 1_748_016_480; // 2025-05-23T16:08:00Z

    #[test]
    fn agent_exact_utc_preserves_fraction_digits_and_instant() {
        for (utc_clock, plus_clock, minus_clock) in [
            (
                "2025-05-23T16:05:00",
                "2025-05-23T20:05:00",
                "2025-05-23T12:05:00",
            ),
            (
                "2020-01-01T10:30:45",
                "2020-01-01T14:30:45",
                "2020-01-01T06:30:45",
            ),
        ] {
            for fraction in ["", ".123", ".123456"] {
                let expected = format!("{utc_clock}{fraction}Z");
                for (clock, offset) in [
                    (utc_clock, "Z"),
                    (utc_clock, "+00:00"),
                    (plus_clock, "+0400"),
                    (minus_clock, "-04:00"),
                ] {
                    let input = format!("{clock}{fraction}{offset}");
                    let shown = present(
                        json!({"updated_at": input.clone()}),
                        PresentationMode::Agent,
                        NOW,
                    );
                    assert_eq!(shown["updated_at"], expected, "{input}");
                    assert_eq!(
                        parse_iso8601_unix(&input),
                        parse_iso8601_unix(&expected),
                        "{input}"
                    );
                }
            }
        }
    }

    #[test]
    fn agent_preserves_timestamp_prefix_body() {
        let body = "2025-05-23T16:05:00Z followed by ordinary message text";
        let shown = present(json!({"content": body}), PresentationMode::Agent, NOW);
        assert_eq!(shown["content"], body);
    }

    #[test]
    fn agent_preserves_offsetless_timestamp() {
        let body = "2025-05-23T16:05:00";
        let shown = present(json!({"content": body}), PresentationMode::Agent, NOW);
        assert_eq!(shown["content"], body);
    }

    #[test]
    fn agent_preserves_malformed_offset() {
        let body = "2025-05-23T16:05:00+25:00";
        let shown = present(json!({"content": body}), PresentationMode::Agent, NOW);
        assert_eq!(shown["content"], body);
    }

    #[test]
    fn agent_list_rows_pair_exact_and_relative_time_in_each_band() {
        let bands = [
            (42, "42s ago"),
            (180, "3m ago"),
            (3 * 3600, "3h ago"),
            (2 * 86400, "2d ago"),
        ];
        let rows: Vec<Value> = bands
            .into_iter()
            .map(|(age, _)| {
                let created = chrono::DateTime::<chrono::Utc>::from_timestamp(NOW - age, 0)
                    .unwrap()
                    .to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
                json!({"created_at": created, "updated_at": created})
            })
            .collect();
        let shown = present(json!({"items": rows.clone()}), PresentationMode::Agent, NOW);
        for (index, (_, relative)) in bands.into_iter().enumerate() {
            assert_eq!(
                shown["items"][index]["created_at"],
                rows[index]["created_at"]
            );
            assert_eq!(
                shown["items"][index]["updated_at"],
                rows[index]["updated_at"]
            );
            assert_eq!(shown["items"][index]["created_at_relative"], relative);
            assert!(shown["items"][index].get("updated_at_relative").is_none());
        }
    }

    #[test]
    fn agent_relative_sibling_obeys_array_properties_existing_and_future_bounds() {
        let recent = "2025-05-23T16:05:00+00:00";
        let future = "2025-05-23T16:08:10Z";
        let shown = present(
            json!({
                "created_at": recent,
                "items": [
                    {"created_at": future},
                    {"created_at": recent, "created_at_relative": "canonical"},
                    {"created_at": "2025-05-23T16:05:00"},
                    {"updated_at": recent},
                    {"created_at": "2025-05-23T16:08:00.000001Z"},
                    {"created_at": "2025-05-23T16:07:59.999999Z"},
                    {"created_at": "2025-05-23T16:08:00.000000Z"},
                    {"properties": [{"created_at": recent, "empty": ""}]}
                ],
                "properties": {"nested": [{"created_at": recent}]}
            }),
            PresentationMode::Agent,
            NOW,
        );
        assert_eq!(shown["created_at"], "2025-05-23T16:05:00Z");
        assert!(shown.get("created_at_relative").is_none());
        assert_eq!(shown["items"][0]["created_at"], future);
        assert!(shown["items"][0].get("created_at_relative").is_none());
        assert_eq!(shown["items"][1]["created_at_relative"], "canonical");
        assert_eq!(shown["items"][2]["created_at"], "2025-05-23T16:05:00");
        assert!(shown["items"][2].get("created_at_relative").is_none());
        assert!(shown["items"][3].get("created_at_relative").is_none());
        assert!(shown["items"][4].get("created_at_relative").is_none());
        assert_eq!(shown["items"][5]["created_at_relative"], "0s ago");
        assert_eq!(shown["items"][6]["created_at_relative"], "0s ago");
        assert_eq!(shown["items"][7]["properties"][0]["created_at"], recent);
        assert!(shown["items"][7]["properties"][0]
            .get("created_at_relative")
            .is_none());
        assert!(shown["items"][7]["properties"][0].get("empty").is_none());
        assert_eq!(shown["properties"]["nested"][0]["created_at"], recent);
        assert!(shown["properties"]["nested"][0]
            .get("created_at_relative")
            .is_none());
    }

    #[test]
    fn agent_relative_sibling_uses_sampled_fraction_within_same_second() {
        let sampled = chrono::DateTime::parse_from_rfc3339("2025-05-23T16:08:00.500000000Z")
            .unwrap()
            .with_timezone(&chrono::Utc);
        let shown = present_with_policy_at(
            json!({"items": [
                {"created_at": "2025-05-23T16:08:00.499999999Z"},
                {"created_at": "2025-05-23T16:08:00.500000000Z"},
                {"created_at": "2025-05-23T16:08:00.5000000000Z"},
                {"created_at": "2025-05-23T16:08:00.5000000001Z"},
                {"created_at": "2025-05-23T16:08:00.500000001Z"},
                {"created_at": "2025-05-23T16:07:59.500000001Z"},
                {"created_at": "2025-05-23T16:07:59.500000000Z"}
            ]}),
            PresentationMode::Agent,
            sampled.into(),
            VerbPresentationPolicy::Standard,
        );
        for index in [0, 1, 2, 5] {
            assert_eq!(shown["items"][index]["created_at_relative"], "0s ago");
        }
        for index in [3, 4] {
            assert!(shown["items"][index].get("created_at_relative").is_none());
        }
        assert_eq!(shown["items"][6]["created_at_relative"], "1s ago");
    }
}