polyc-rpc-client 2026.7.1

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

#![forbid(unsafe_code)]
#![warn(missing_docs)]

pub mod edge;
pub use edge::{EdgeAdapter, IngressDirective, Priority, build_attribution};

use std::sync::Arc;

use connectrpc::client::{ClientConfig, HttpClient};
use futures::Stream;
use polyc_agent::text_message;
use polyc_proto::proto::polychrome::agent::v1::{
    AgentEnd, AgentRequest, AgentServiceClient, AgentStart, ClassifyRequest,
    CompactionReason as WireCompactionReason, ContextCompacted,
    IngressDirective as WireIngressDirective, InterruptRequest, Message, ParticipantMessage,
    PendingApproval as WireAgentPendingApproval, TurnFailureKind as WireTurnFailureKind, Verdict,
    agent_response, content, tool_call_content,
};
use polyc_proto::proto::polychrome::approval::v1::{
    ApprovalResponseRequest, ApprovalServiceClient, ListPendingRequest, PendingApprovalEntry,
};
use polyc_proto::proto::polychrome::ops::v1::{
    AckRequest, DecideRequest, NotificationServiceClient, OperatorMailboxServiceClient,
    PollPendingRequest, SubscribeRequest, decide_reply, ops_action_view, upgrade_outcome,
};
use polyc_proto::proto::polychrome::persona::v1::{
    AdminInviteRequest, AutoLinkOutcome, AutoLinkRequest, CompleteLinkRequest, DescribeRequest,
    LinkOutcome, PersonaServiceClient, SetIncognitoRequest, StartDeepLinkRequest, StartLinkRequest,
};
use polyc_proto::proto::polychrome::routine::v1::{
    ListLiveEnrollmentsRequest, RoutineServiceClient, StartEnrollmentRequest,
};

/// Errors an agent dial can produce.
#[derive(Debug, thiserror::Error)]
pub enum DialError {
    /// Could not parse the configured agent address as a URI.
    #[error("invalid agent address {addr:?}: {source}")]
    InvalidAddress {
        /// The address string that failed to parse.
        addr: String,
        /// The underlying URI parse error.
        #[source]
        source: http::uri::InvalidUri,
    },
    /// Building the TLS client for an `https://` endpoint failed (e.g. no
    /// process-default crypto provider). The dial fails closed rather than
    /// silently downgrading to plaintext.
    #[error("tls setup failed for agent address: {0}")]
    Tls(String),
    /// Connect-level error from the `AgentService` stream.
    #[error(transparent)]
    Connect(#[from] connectrpc::ConnectError),
}

impl DialError {
    /// The Connect error code, when this is a transport-level Connect error
    /// (`None` for local address/TLS-setup failures).
    #[must_use]
    pub const fn code(&self) -> Option<connectrpc::ErrorCode> {
        match self {
            Self::Connect(e) => Some(e.code),
            Self::InvalidAddress { .. } | Self::Tls(_) => None,
        }
    }

    /// Whether retrying the call could plausibly succeed. Only transient
    /// transport conditions are retryable; terminal codes
    /// (`InvalidArgument`, `Unauthenticated`, `NotFound`, …) and local
    /// address/TLS failures are not. Edges use this to decide whether to ask
    /// the source platform to redeliver (retryable) or to drop / 4xx
    /// (terminal — redelivery would loop forever).
    #[must_use]
    pub const fn is_retryable(&self) -> bool {
        matches!(
            self.code(),
            Some(
                connectrpc::ErrorCode::Unavailable
                    | connectrpc::ErrorCode::DeadlineExceeded
                    | connectrpc::ErrorCode::ResourceExhausted
                    | connectrpc::ErrorCode::Aborted
            )
        )
    }
}

/// Default per-call deadline for an agent turn (emitted as `Connect-Timeout-Ms`
/// on every dial). Turns can be long (tool loops, slow providers), so this is
/// generous; edges add their own outer `tokio::time::timeout` for defence.
const AGENT_DIAL_TIMEOUT: std::time::Duration = std::time::Duration::from_mins(3);

/// Default per-call deadline for the short control-plane RPCs (approval
/// responses, persona lookups/ceremonies). These never run a turn.
const CONTROL_DIAL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// Bound the TCP connect phase of every control-plane dial so a dead or
/// terminating peer fails fast (surfaced as `Unavailable`) instead of
/// blackholing the SYN for the kernel `tcp_syn_retries` (~130s). Bounds only
/// `connect(2)`; DNS and TLS handshake are covered by the per-call deadline.
/// Mirrors the `CONNECT_TIMEOUT` const in the llm-vertex / llm-openai clients.
const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// Build the Connect HTTP transport for `uri`, honoring its scheme: `https`
/// dials over TLS (OS trust store); anything else (incl. a scheme-less
/// `host:port`) uses plaintext. An `https` address is **never** silently
/// downgraded — a TLS build failure surfaces as [`DialError::Tls`].
///
/// No `pool_idle_timeout` is configured here (`#757` follow-up): this
/// `HttpClient` pools connections through hyper's legacy client, whose
/// `Client::builder` already defaults `pool_idle_timeout` to 90 seconds (see
/// `hyper_util::client::legacy::client::Config::default`) — comfortably under
/// any realistic gap between calls, so a connection genuinely idle in the pool
/// is already reaped rather than blackholed. connectrpc 0.8.1's
/// `HttpClientBuilder` doesn't expose a way to change this default anyway
/// (verified against its source — there is no `pool_idle_timeout` method).
fn http_client_for(uri: &http::Uri) -> Result<HttpClient, DialError> {
    if uri.scheme_str() == Some("https") {
        use rustls_platform_verifier::ConfigVerifierExt;
        let tls = rustls::ClientConfig::with_platform_verifier()
            .map_err(|e| DialError::Tls(e.to_string()))?;
        Ok(HttpClient::builder()
            .connect_timeout(CONNECT_TIMEOUT)
            .with_tls(std::sync::Arc::new(tls)))
    } else {
        Ok(HttpClient::builder()
            .connect_timeout(CONNECT_TIMEOUT)
            .plaintext())
    }
}

/// Per-call options carrying the active span's W3C `traceparent`, so the
/// control-plane handler re-parents on this turn's span instead of starting a
/// fresh trace. Cheap when no propagator is installed (the global getter is a
/// no-op and no header is set). The per-call deadline comes from the client's
/// `with_default_timeout`, so it need not be repeated here.
fn traced_options() -> connectrpc::client::CallOptions {
    let mut headers = http::HeaderMap::new();
    polyc_runtime::propagation::inject_current_span_into(&mut headers);
    connectrpc::client::CallOptions::default()
        .with_headers(headers.into_iter().filter_map(|(n, v)| n.map(|n| (n, v))))
}

/// Why a turn's prompt was auto-compacted before it ran. The buffered analog
/// of [`WireCompactionReason`], lifted to a closed Rust enum so surfaces match
/// on it without touching the wire crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompactionReason {
    /// Older turns were folded into an anchored-iterative summary
    /// (message-count trigger). The summary survives as the prompt's preamble.
    Summarized,
    /// Older tool-output payloads were trimmed to fit the token budget
    /// (char/token-budget trigger). No messages were dropped, only their bulk.
    ///
    /// NOTE: the control plane no longer EMITS this reason — the retroactive
    /// tool-output truncation layer was removed in favor of token-budget
    /// summarization (the per-call tool-output cap now bounds individual tool
    /// results). This variant is retained as a never-emitted-on-happy-path
    /// decode path so any old persisted/wire value still maps (the enum stays
    /// exhaustive) and an unknown future wire reason has a quiet fallback.
    Truncated,
}

impl CompactionReason {
    /// Canonical one-line headline (with a leading glyph) for a pre-turn
    /// compaction notice, shared by every edge so the user-facing wording can't
    /// drift between Slack, Telegram, and the rest. `summarized_messages` is used
    /// only by [`Self::Summarized`]. Returns PLAIN text — no markup — so each
    /// surface applies its own emphasis/escaping (Slack `_…_` mrkdwn, Telegram
    /// `*…*`, …) without double-formatting.
    #[must_use]
    pub fn notice_headline(self, summarized_messages: u32) -> String {
        match self {
            Self::Summarized => {
                let plural = if summarized_messages == 1 { "" } else { "s" };
                format!(
                    "🧠 Summarized {summarized_messages} earlier message{plural} to keep the \
                     conversation manageable"
                )
            }
            Self::Truncated => {
                "✂️ Trimmed earlier tool output to keep the conversation manageable".to_owned()
            }
        }
    }
}

/// Incremental event emitted while a turn streams from the control plane.
///
/// Unlike [`AgentDialer::run_turn`], which folds the whole turn into one
/// string, the streaming API surfaces each meaningful step as it arrives so a
/// live surface (e.g. Slack `chat.appendStream`) can update in place.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TurnEvent {
    /// The turn's context was auto-compacted before it ran. Emitted ONCE, as
    /// the first event of the turn (before any [`TurnEvent::TextDelta`]), so a
    /// live surface can render a brief notice rather than letting earlier work
    /// silently vanish from the model's view. The full transcript is retained
    /// server-side; only this turn's prompt was compacted.
    ContextCompacted {
        /// Whether the context was summarized or truncated.
        reason: CompactionReason,
        /// Earlier messages folded into the summary (0 when truncated).
        summarized_messages: u32,
        /// Short preview of the surviving summary; empty when truncated.
        summary_preview: String,
    },
    /// Incremental assistant answer text (model/assistant role).
    TextDelta(String),
    /// A tool call has started, named for a user-visible "thinking step".
    ToolStarted {
        /// The tool/function name, or the call id when the name is absent.
        name: String,
    },
    /// The turn paused before executing a tool that requires human approval.
    /// Emitted (one per pending call) from the terminal `AgentEnd` just before
    /// [`TurnEvent::Done`]. The caller submits a decision via
    /// `ApprovalService.Respond` (the THIN path) and re-drives the turn.
    ApprovalPending {
        /// Tool-call id == the approval `request_id` to answer.
        request_id: String,
        /// The tool/function name awaiting approval. Raw machine identifier;
        /// the field of record for trust/audit.
        tool_name: String,
        /// Human display label (MCP-style `title`) for the tool, for rendering
        /// in the approval prompt. May be empty; the surface then derives one
        /// from `tool_name`.
        title: String,
        /// Arguments JSON for the call.
        args_json: String,
        /// Why this call is gated, when the pause is an OVERRIDE of a call that
        /// would not otherwise need approval. Empty for an ordinary gated call;
        /// non-empty only for the lethal-trifecta / Rule-of-Two containment
        /// override — rendered on the approval card so the approver sees that
        /// untrusted content is in context and this is an outbound call.
        reason: String,
        /// Short-lived signed capability (`#787`), freshly minted for THIS
        /// card and scoped to `request_id` + the conversation it belongs to.
        /// Opaque to the caller: carry it back unmodified to
        /// [`ApprovalDialer::respond`]. `ApprovalService.Respond` rejects a
        /// decision whose token is missing, expired, or bound to a different
        /// request or conversation.
        resolve_token: String,
    },
    /// The turn suspended to delegate to a sub-agent: the model invoked the
    /// reserved `__handoff_to` primitive. Surfaced (once) from the terminal
    /// `AgentEnd.handoff` just before [`TurnEvent::Done`]. The child
    /// conversation runs independently; the parent resumes when the child
    /// returns, so an edge can render "delegating…" rather than going silent.
    HandoffStarted {
        /// The child agent / planner chosen; empty selects the parent's
        /// default planner.
        child_agent_id: String,
        /// Free-form reason captured for operator visibility.
        reason: String,
    },
    /// The control plane minted an admin invite this turn for the edge to
    /// deliver privately (agent-evaluable admin invite, `#698`). Surfaced from
    /// the terminal [`AgentEnd`] just before [`TurnEvent::Done`]. The edge opens
    /// the target's direct message and delivers the `code` there — and ONLY
    /// there. The code reached neither the agent nor a channel; the edge fails
    /// closed (telling the admin, delivering nothing) if it can't reach the
    /// target privately.
    InviteDelivery {
        /// The target's provider-native user id (from the mention markup). The
        /// edge opens THIS person's direct message.
        target_user_id: String,
        /// The single-use invite code — the one secret on this event. Deliver it
        /// only to the target's direct message; never log it or post it to a
        /// channel.
        code: String,
        /// The inviting admin's display name, for the target-facing copy. May be
        /// empty; the edge then uses a neutral phrasing.
        inviter_display: String,
    },
    /// A paid tool call this turn needed a linked wallet (`#519`). Surfaced
    /// from the terminal [`AgentEnd`] just before [`TurnEvent::Done`]. Carries
    /// only the URL — no copy — so every edge renders the identical "Link a
    /// wallet" card text through the shared `polyc_proto` helpers instead of
    /// hand-writing its own wording.
    WalletLinkPrompt {
        /// The deployment's wallet-link URL, when known. `None` = point the
        /// reader at an admin instead of rendering a dangling button.
        link_url: Option<String>,
    },
    /// `persona_credential_setup` minted a fresh persona-signing passkey
    /// enrollment link this turn (PRD #767). Surfaced from the terminal
    /// [`AgentEnd`] just before [`TurnEvent::Done`]. Carries only the URL —
    /// no copy — so every edge renders the identical "Set up passkey" card
    /// text through the shared `polyc_proto` helpers instead of hand-writing
    /// its own wording.
    PersonaCredentialPrompt {
        /// The one-time enrollment-ceremony URL. Always `Some` and non-empty
        /// when this variant is emitted — unlike [`TurnEvent::WalletLinkPrompt`]
        /// there is no "no link available" card variant.
        link_url: Option<String>,
    },
    /// The turn failed durably instead of completing (`#756`). Surfaced from
    /// the terminal [`AgentEnd.failure`](AgentEnd) just before
    /// [`TurnEvent::Done`] — a structured, durable fact the control plane
    /// persisted, not merely the Connect RPC status a dial error would carry.
    /// `AgentEnd.failure` exists specifically so "external surfaces (Slack,
    /// the cockpit) can react" (see its wire doc comment); before this
    /// variant existed, no edge ever read it, and a durably-failed turn with
    /// no other content (no messages, no pending approvals, no handoff, no
    /// invites) surfaced as silence — every edge saw `Done` with nothing to
    /// show and posted nothing.
    TurnFailed {
        /// Provider-agnostic failure classification (mirrors the wire
        /// `TurnFailureKind` 1:1; `TURN_FAILURE_KIND_UNSPECIFIED` maps to
        /// [`TurnFailureKind::Other`] — a definite failure with an unknown
        /// reason is still a definite failure).
        kind: TurnFailureKind,
        /// Human-readable diagnostic text (the underlying provider/tool
        /// error). Log-only — an edge's user-facing wording comes from its
        /// own shared failure-notice helper keyed on
        /// [`TurnFailureKind::is_retryable`], not this string.
        message: String,
    },
    /// Terminal event: the turn has ended and no further events follow.
    Done,
}

/// Provider-agnostic classification of a durable turn failure (`#756`).
///
/// Local mirror of the wire `TurnFailureKind`, following the same
/// decouple-edges-from-the-wire-schema convention as [`CompactionReason`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TurnFailureKind {
    /// The provider rejected the call for exceeding its rate limit.
    RateLimit,
    /// The call exceeded its deadline.
    Timeout,
    /// The provider or a dependency it needs was unreachable.
    Unavailable,
    /// A credential/authentication failure.
    Auth,
    /// The request itself was invalid.
    BadRequest,
    /// Any other failure, including an unspecified wire kind.
    Other,
}

impl TurnFailureKind {
    /// Whether retrying the call could plausibly succeed, mirroring
    /// [`DialError::is_retryable`]'s transient-vs-terminal split: a provider
    /// hiccup (rate limit, timeout, unavailable) is worth retrying; a
    /// credential or malformed-request failure will fail identically again,
    /// and an unclassified `Other` failure is treated conservatively as
    /// non-retryable rather than implying a resend will help when it's
    /// unknown whether it would.
    #[must_use]
    pub const fn is_retryable(self) -> bool {
        matches!(self, Self::RateLimit | Self::Timeout | Self::Unavailable)
    }
}

/// Reusable handle for dialing the polychrome control plane.
#[derive(Clone)]
pub struct AgentDialer {
    client: Arc<AgentServiceClient<HttpClient>>,
}

impl AgentDialer {
    /// Build a dialer pointed at `addr` (expects `http://host:port`).
    ///
    /// # Errors
    ///
    /// Returns [`DialError::InvalidAddress`] if `addr` isn't a valid URI.
    pub fn new(addr: &str) -> Result<Self, DialError> {
        let uri = addr
            .parse::<http::Uri>()
            .map_err(|source| DialError::InvalidAddress {
                addr: addr.to_owned(),
                source,
            })?;
        let http = http_client_for(&uri)?;
        let config = ClientConfig::new(uri).with_default_timeout(AGENT_DIAL_TIMEOUT);
        let client = AgentServiceClient::new(http, config);
        Ok(Self {
            client: Arc::new(client),
        })
    }

    /// Build an [`ApprovalDialer`] for the SAME control-plane endpoint.
    /// `AgentService` and `ApprovalService` are served on one Connect port, so
    /// an approval client reuses the agent address — callers that already hold
    /// an `AgentDialer` don't need to thread a second address.
    ///
    /// # Errors
    /// Returns [`DialError::InvalidAddress`] if `addr` isn't a valid URI.
    pub fn approval_dialer(addr: &str) -> Result<ApprovalDialer, DialError> {
        ApprovalDialer::new(addr)
    }

    /// Run one turn against the control plane and collect the aggregated
    /// text response.
    ///
    /// `conversation_id` is the stable id for the conversation (the Slack
    /// adapter derives it from the thread; the CLI takes it as an argument).
    /// `user_text` is the user message with any bot mention already stripped.
    /// Returns the concatenated assistant text across every batch in the
    /// response stream, or `Ok(String::new())` if the turn produced no text.
    /// Non-text content variants (tool calls, tool results, thoughts) are
    /// rendered as bracketed placeholders.
    ///
    /// # Errors
    ///
    /// Returns [`DialError::Connect`] for any transport/stream/encoding
    /// error from the `AgentService` call.
    pub async fn run_turn(
        &self,
        conversation_id: &str,
        exec_id: &str,
        user_text: &str,
    ) -> Result<String, DialError> {
        self.run_turn_with(conversation_id, exec_id, user_text, Attribution::default())
            .await
    }

    /// Like [`run_turn`](Self::run_turn) but attributes the turn to a caller
    /// (and participants). Non-streaming edges that resolve an identity via
    /// [`EdgeAdapter::caller`] use this so their turns populate
    /// `AgentStart.caller` (persona attribution) — the buffered analog of
    /// [`run_turn_streaming_messages_with`](Self::run_turn_streaming_messages_with).
    ///
    /// # Errors
    ///
    /// Returns [`DialError::Connect`] for any transport/stream/encoding error.
    pub async fn run_turn_with(
        &self,
        conversation_id: &str,
        exec_id: &str,
        user_text: &str,
        attribution: Attribution,
    ) -> Result<String, DialError> {
        Ok(self
            .run_turn_with_approvals(
                conversation_id,
                exec_id,
                user_text,
                attribution,
                IngressDirective::default(),
            )
            .await?
            .reply)
    }

    /// Like [`run_turn_with`](Self::run_turn_with) but ALSO surfaces any
    /// [`PendingApprovalPrompt`]s the turn paused on, mirroring the streaming
    /// path's [`TurnEvent::ApprovalPending`] projection of the same terminal
    /// `AgentEnd.pending_approvals` field.
    ///
    /// Buffered edges (Discord/email/trigger/A2A) that don't drive the
    /// streaming API still need to render an approve/deny affordance instead
    /// of losing a gated call to the scaffolding-placeholder fallback — this
    /// is the buffered-API variant that lets them. Call
    /// [`ApprovalDialer::respond`] for a decision, then re-drive with this
    /// same method (empty `user_text`) to resume the turn.
    ///
    /// `ingress_directive` is the edge's own policy for this turn (`#68`) —
    /// a step-budget cap, an advisory priority, and/or a required approver.
    /// An edge with no such policy passes [`IngressDirective::default`]
    /// (empty; byte-for-byte unaffected).
    ///
    /// # Errors
    ///
    /// Returns [`DialError::Connect`] for any transport/stream/encoding
    /// error from the `AgentService` call.
    pub async fn run_turn_with_approvals(
        &self,
        conversation_id: &str,
        exec_id: &str,
        user_text: &str,
        attribution: Attribution,
        ingress_directive: IngressDirective,
    ) -> Result<BufferedTurn, DialError> {
        let request = build_request(
            conversation_id,
            exec_id,
            vec![text_message("user", user_text)],
            None,
            attribution,
            false,
            ingress_directive,
            "",
        );
        self.run_turn_buffered_request(request).await
    }

    /// Drive one **routine fire** turn: like
    /// [`run_turn_with_approvals`](Self::run_turn_with_approvals), but the
    /// conversation declares ephemeral history (#843), so the control plane
    /// starts the model on an empty transcript instead of replaying prior fires.
    /// Used by the trigger edge's fan-out — each periodic firing is independent,
    /// never re-feeding past digests / tool loops into context. The event log
    /// still records every fire for forensics, and a gated call still surfaces
    /// its [`PendingApprovalPrompt`]s so the pause is discoverable.
    ///
    /// `ingress_directive` is the edge's own policy for this firing (`#68`) —
    /// see [`Self::run_turn_with_approvals`]. The trigger edge maps a
    /// `Routine`'s configured step budget into it; every other caller passes
    /// [`IngressDirective::default`].
    ///
    /// `occurrence` is the scheduled tick that produced this firing (`#1103`,
    /// INV-2) — the trigger edge derives it from the firing job's stable
    /// identity and forwards it here, so the control plane can refuse to
    /// dispatch a second turn for the same tick (redelivery/overlap dedup,
    /// INV-3). An empty string is an unidentified firing (a manual send) and
    /// never dedups.
    ///
    /// # Errors
    ///
    /// Returns [`DialError::Connect`] for any transport/stream/encoding error.
    pub async fn run_routine_turn(
        &self,
        conversation_id: &str,
        exec_id: &str,
        user_text: &str,
        attribution: Attribution,
        ingress_directive: IngressDirective,
        occurrence: &str,
    ) -> Result<BufferedTurn, DialError> {
        let request = build_request(
            conversation_id,
            exec_id,
            vec![text_message("user", user_text)],
            None,
            attribution,
            true,
            ingress_directive,
            occurrence,
        );
        self.run_turn_buffered_request(request).await
    }

    /// Open the connect stream for one pre-built request and fold the
    /// response envelopes into a [`BufferedTurn`] — the single transport body
    /// [`run_turn_with`](Self::run_turn_with) and
    /// [`run_turn_with_approvals`](Self::run_turn_with_approvals) share, so
    /// the two buffered call sites can't drift on what a terminal `AgentEnd`
    /// means.
    async fn run_turn_buffered_request(
        &self,
        request: AgentRequest,
    ) -> Result<BufferedTurn, DialError> {
        let mut stream = self
            .client
            .connect_with_options(request, traced_options())
            .await?;
        // The assistant's prose answer. Tool calls, tool results, and thoughts
        // are intermediate scaffolding — they're aggregated separately and only
        // surfaced when the turn produced no text at all (e.g. a turn that ends
        // on a tool_call / approval pause), so a normal answer reads cleanly
        // instead of "[tool_call:…]\n[tool_result:…]\nIt is 3pm."
        let mut text_parts: Vec<String> = Vec::new();
        let mut scaffolding: Vec<String> = Vec::new();
        // A paid call this turn needed a linked wallet (`#519`): absent by
        // default, `Present(url)` once `AgentEnd` carries the signal.
        let mut wallet_link_prompt = WalletLinkPrompt::None;
        // `persona_credential_setup` minted a fresh enrollment link this turn
        // (PRD #767): `None` by default, `Some(url)` once `AgentEnd` carries
        // the signal. Always a real URL when `Some` — unlike
        // `wallet_link_prompt` there is no "unknown URL" tri-state to model.
        let mut persona_credential_prompt: Option<String> = None;
        // Gated calls the turn paused on (`AgentEnd.pending_approvals`) — the
        // buffered analog of the streaming path's `TurnEvent::ApprovalPending`
        // (`events_from_end`). Empty unless the turn paused.
        let mut pending_approvals: Vec<PendingApprovalPrompt> = Vec::new();
        while let Some(view) = stream.message().await? {
            let response = view.to_owned_message();
            match response.r#type {
                Some(agent_response::Type::Outputs(outputs)) => {
                    for msg in outputs.messages {
                        aggregate_output_message(msg, &mut text_parts, &mut scaffolding);
                    }
                }
                // `End` carries the turn's answer already folded into
                // `text_parts`/`scaffolding` above; `wallet_link_prompt` and
                // `pending_approvals` mirror the streaming path's identical
                // projection (`events_from_end`) so the buffered and
                // streaming APIs cannot drift on either signal. A pre-turn
                // compaction notice carries no answer text; an empty
                // envelope is defensive (the wire allows it). Deliberately
                // NOT a `break` on `End`: returning there would close our
                // half of the stream while the transport may still have
                // frames (or only its trailer) in flight, which registers as
                // a client-cancelled call to anything that inspects gRPC
                // status on this path. Keep reading — mirrors the
                // drain-to-EOF shape in `harness_dialer::run_turn_streamed`
                // — until `stream.message()` itself returns `None` at
                // transport EOF.
                Some(agent_response::Type::End(end)) => {
                    if let Some(prompt) = end.wallet_link_prompt.into_option() {
                        let link_url =
                            (!prompt.link_url.trim().is_empty()).then_some(prompt.link_url);
                        wallet_link_prompt = WalletLinkPrompt::Present(link_url);
                    }
                    if let Some(prompt) = end.persona_credential_prompt.into_option() {
                        let link_url =
                            (!prompt.link_url.trim().is_empty()).then_some(prompt.link_url);
                        persona_credential_prompt = link_url;
                    }
                    pending_approvals = end
                        .pending_approvals
                        .into_iter()
                        .map(PendingApprovalPrompt::from)
                        .collect();
                }
                Some(agent_response::Type::Compacted(_)) | None => {}
            }
        }
        Ok(BufferedTurn {
            reply: finalize_buffered_reply(
                &text_parts,
                &scaffolding,
                wallet_link_prompt,
                persona_credential_prompt.as_deref(),
            ),
            pending_approvals,
        })
    }

    /// Run one turn against the control plane and stream each meaningful step
    /// as a [`TurnEvent`], for live surfaces that update in place.
    ///
    /// The request is built identically to [`AgentDialer::run_turn`]; see that
    /// method for the meaning of `conversation_id`, `exec_id`, and
    /// `user_text`. The returned stream yields:
    ///
    /// - [`TurnEvent::TextDelta`] for each model/assistant-role text block,
    /// - [`TurnEvent::ToolStarted`] when a tool call begins, and
    /// - [`TurnEvent::Done`] once at end-of-turn, after which the stream ends.
    ///
    /// Tool-role result echoes and empty/non-textual blocks produce no event.
    ///
    /// # Errors
    ///
    /// The outer `Result` carries a [`DialError::Connect`] if opening the
    /// stream fails. Each item is a `Result` so per-message transport/decode
    /// errors surface inline without tearing down the whole stream type.
    pub async fn run_turn_streaming(
        &self,
        conversation_id: &str,
        exec_id: &str,
        user_text: &str,
    ) -> Result<impl Stream<Item = Result<TurnEvent, DialError>>, DialError> {
        self.run_turn_streaming_messages(
            conversation_id,
            exec_id,
            vec![text_message("user", user_text)],
        )
        .await
    }

    /// Like [`Self::run_turn_streaming`] but takes a pre-built (e.g. attributed
    /// multi-party) message list as the turn input.
    ///
    /// # Errors
    ///
    /// Returns [`DialError::Connect`] for any transport/stream/encoding error.
    pub async fn run_turn_streaming_messages(
        &self,
        conversation_id: &str,
        exec_id: &str,
        messages: Vec<Message>,
    ) -> Result<impl Stream<Item = Result<TurnEvent, DialError>>, DialError> {
        self.run_turn_streaming_messages_with(
            conversation_id,
            exec_id,
            messages,
            None,
            Attribution::default(),
            IngressDirective::default(),
        )
        .await
    }

    /// The full-fidelity variant: one method carries everything a turn's
    /// request can — a settled inbound [`PaymentReceipt`] (the control plane
    /// persists a signed `payment_receipt` event in the turn's atomic batch),
    /// the caller [`Attribution`] (resolved to durable personas and recorded
    /// as `caller`/`participant` events), and the edge's own
    /// [`IngressDirective`] (`#68`) — a step-budget cap, an advisory
    /// priority, and/or a required approver. One method rather than a matrix
    /// of variants, so a paid *and* attributed *and* directed edge can't
    /// silently drop one of the three. An edge with no ingress policy passes
    /// [`IngressDirective::default`].
    ///
    /// # Errors
    ///
    /// Returns [`DialError::Connect`] for any transport/stream/encoding error.
    pub async fn run_turn_streaming_messages_with(
        &self,
        conversation_id: &str,
        exec_id: &str,
        messages: Vec<Message>,
        payment_receipt: Option<PaymentReceipt>,
        attribution: Attribution,
        ingress_directive: IngressDirective,
    ) -> Result<impl Stream<Item = Result<TurnEvent, DialError>>, DialError> {
        let request = build_request(
            conversation_id,
            exec_id,
            messages,
            payment_receipt,
            attribution,
            false,
            ingress_directive,
            "",
        );
        self.run_turn_streaming_request(request).await
    }

    /// Open the connect stream for one pre-built request and project the
    /// response envelopes into [`TurnEvent`]s — the single transport body
    /// every streaming variant shares.
    async fn run_turn_streaming_request(
        &self,
        request: AgentRequest,
    ) -> Result<impl Stream<Item = Result<TurnEvent, DialError>>, DialError> {
        let mut stream = self
            .client
            .connect_with_options(request, traced_options())
            .await?;
        Ok(async_stream::try_stream! {
            // Set once an explicit `AgentEnd` has been seen and its events
            // (including the terminal `Done`) have been yielded, so the
            // fallback below doesn't yield a second `Done`.
            let mut ended = false;
            while let Some(view) = stream.message().await? {
                let response = view.to_owned_message();
                match response.r#type {
                    // A pre-turn compaction notice, surfaced before any text so
                    // the live surface can flag it ahead of the answer.
                    Some(agent_response::Type::Compacted(c)) => {
                        yield event_from_compacted(*c);
                    }
                    Some(agent_response::Type::Outputs(outputs)) => {
                        for msg in outputs.messages {
                            if let Some(event) = message_to_event(msg) {
                                yield event;
                            }
                        }
                    }
                    Some(agent_response::Type::End(end)) => {
                        // The terminal envelope's extensions (pending approvals,
                        // a sub-agent handoff) surface before the terminal Done
                        // so a live surface can prompt / show "delegating…".
                        for event in events_from_end(*end) {
                            yield event;
                        }
                        ended = true;
                        // Deliberately NOT a `return`: returning here would
                        // drop our half of the stream while the transport may
                        // still have frames (or only its trailer) in flight,
                        // which registers as a client-cancelled call to
                        // anything that inspects gRPC status on this path.
                        // Keep reading — mirrors the drain-to-EOF shape in
                        // `harness_dialer::run_turn_streamed` — until
                        // `stream.message()` itself returns `None` at
                        // transport EOF.
                    }
                    // Empty envelope — defensive; ignore (mirrors `run_turn`).
                    None => {}
                }
            }
            // Stream closed without an explicit AgentEnd: still signal a
            // terminal event so the caller can finalise the live surface.
            if !ended {
                yield TurnEvent::Done;
            }
        })
    }

    /// Ask the control plane's participation gate whether to reply to the
    /// latest message of a (multi-party) thread. Returns `true` only on
    /// `respond`; `notify` / `ignore` map to `false` (stay silent). The gate
    /// runs a cheap classifier model server-side and never runs a turn.
    ///
    /// # Errors
    ///
    /// Returns [`DialError::Connect`] for any transport/encoding error.
    pub async fn should_respond(
        &self,
        conversation_id: &str,
        bot_name: &str,
        transcript: Vec<ParticipantMessage>,
    ) -> Result<bool, DialError> {
        let request = ClassifyRequest {
            conversation_id: conversation_id.to_owned(),
            bot_name: bot_name.to_owned(),
            transcript,
            ..Default::default()
        };
        let resp = self
            .client
            .classify_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(resp.verdict.to_i32() == Verdict::VERDICT_RESPOND as i32)
    }

    /// Cancel the conversation's in-flight turn without dropping a Connect
    /// stream. Returns `true` if a running turn was found and signalled to
    /// cancel; `false` is the idempotent no-op (no turn running on the replica
    /// that served this call).
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error.
    pub async fn interrupt(&self, conversation_id: &str) -> Result<bool, DialError> {
        let request = InterruptRequest {
            conversation_id: conversation_id.to_owned(),
            ..Default::default()
        };
        let resp = self
            .client
            .interrupt_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(resp.interrupted)
    }
}

/// A human's decision on a pending approval, as the edges present it.
///
/// One enum instead of a widening tuple of booleans, so an edge maps its button
/// once and its accessors ([`Self::approved`], [`Self::approved_for_session`],
/// [`Self::is_abort`]) yield the flags [`ApprovalDialer::respond`] takes — the
/// two can't drift.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApprovalChoice {
    /// Run this one call; ask again next time.
    Approve,
    /// Run it AND remember the approval for the caller's session ("don't ask
    /// again") — honored only for idempotent tools.
    ApproveForSession,
    /// Decline this call; the turn continues (a synthetic denial result).
    Deny,
    /// Decline this call AND stop the turn — the edge does not re-drive.
    Abort,
    /// Send the call back without approving or denying it (#67): the pause is
    /// recorded as deferred but stays open for a later decision.
    Defer,
}

impl ApprovalChoice {
    /// Whether the call was approved (approve or approve-for-session).
    #[must_use]
    pub const fn approved(self) -> bool {
        matches!(self, Self::Approve | Self::ApproveForSession)
    }

    /// Whether the approval is remembered for the session.
    #[must_use]
    pub const fn approved_for_session(self) -> bool {
        matches!(self, Self::ApproveForSession)
    }

    /// Whether the turn should stop (no re-drive).
    #[must_use]
    pub const fn is_abort(self) -> bool {
        matches!(self, Self::Abort)
    }

    /// Whether the call was deferred ("send back", #67) — neither approved nor
    /// denied; recorded but left pending.
    #[must_use]
    pub const fn is_defer(self) -> bool {
        matches!(self, Self::Defer)
    }
}

/// The one line of copy shown after a human decides a pending approval.
///
/// Shared by every edge so the identical state reads identically everywhere
/// (Slack replaces the approval card with this; Telegram edits the prompt
/// message to this). `label` is the tool's friendly display name, already
/// resolved by the caller (title, or a `polyc_proto::humanize_tool_name`
/// fallback).
#[must_use]
pub fn approval_decided_text(label: &str, choice: ApprovalChoice, decider: &str) -> String {
    match choice {
        ApprovalChoice::ApproveForSession => format!(
            "✅ Approved by {decider} — running \"{label}\"… (won't ask again this session)"
        ),
        ApprovalChoice::Approve => format!("✅ Approved by {decider} — running \"{label}\""),
        ApprovalChoice::Deny => format!("🚫 Denied by {decider}\"{label}\" was not run."),
        ApprovalChoice::Abort => {
            format!("🛑 Aborted by {decider}\"{label}\" was not run; the turn was stopped.")
        }
        ApprovalChoice::Defer => {
            format!("↩️ Sent back by {decider}\"{label}\" is still waiting for a decision.")
        }
    }
}

/// The one line of copy shown once an approved call's re-drive has actually
/// executed (`#743`).
///
/// The sibling of [`approval_decided_text`] one step later in the lifecycle:
/// that function's "running…" line covers the gap between the decision and
/// execution; this replaces it once the runtime knows the outcome, so the
/// card never sits on a stale "running…" after the tool has already
/// finished. `label` is the tool's friendly display name (title, or a
/// `humanize_tool_name` fallback), `decider` is who approved it, and
/// `success` distinguishes a clean run from one that errored — the runtime,
/// not the model, owns this line: it is built from the actual dispatch
/// outcome, never from anything the model said.
#[must_use]
pub fn approval_completed_text(label: &str, decider: &str, success: bool) -> String {
    if success {
        format!("✅ Approved by {decider}\"{label}\" is done.")
    } else {
        format!("✅ Approved by {decider}\"{label}\" ran but hit an error.")
    }
}

/// The persisted outcome of an `ApprovalService.Respond` call.
///
/// On the THIN path the control plane is the signer: the caller submits an
/// UNSIGNED decision and the control plane appends a server-signed
/// `approval_response` event, returning the signature so the caller can show /
/// audit a verifiable outcome.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApprovalOutcome {
    /// `true` if a matching pending request existed and the response was
    /// persisted; `false` is the idempotent no-op (already answered / unknown).
    pub persisted: bool,
    /// Lowercase-hex ed25519 signature over the canonical response bytes.
    pub signature_hex: String,
    /// Lowercase-hex public key the signature verifies against.
    pub signed_by_hex: String,
}

impl From<polyc_proto::proto::polychrome::approval::v1::ApprovalResponseReply> for ApprovalOutcome {
    fn from(reply: polyc_proto::proto::polychrome::approval::v1::ApprovalResponseReply) -> Self {
        Self {
            persisted: reply.persisted,
            signature_hex: reply.signature_hex,
            signed_by_hex: reply.signed_by_hex,
        }
    }
}

/// One outstanding approval returned by [`ApprovalDialer::list_pending`].
///
/// Carries the fields an edge needs to re-render an Approve/Deny prompt for a
/// `request_id` it lost (e.g. the streamed `ApprovalPending` event never arrived).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingApproval {
    /// The id to answer via [`ApprovalDialer::respond`].
    pub request_id: String,
    /// The raw tool name the approval gates.
    pub tool_name: String,
    /// The tool-call arguments (JSON), for rendering the prompt.
    pub args_json: String,
    /// The override gate reason the durable `approval_request` recorded — empty
    /// for an ordinary gated call, non-empty for the lethal-trifecta /
    /// Rule-of-Two containment override. Lets a recovered card show the same
    /// explanation the live `ApprovalPending` event carried.
    pub reason: String,
    /// Short-lived signed capability (`#787`), freshly minted for THIS
    /// listing and scoped to `request_id` + the conversation it belongs to.
    /// Carry it back unmodified to [`ApprovalDialer::respond`].
    pub resolve_token: String,
}

/// `approval.v1.PendingApprovalEntry` has no `title` field (unlike
/// `agent.v1.PendingApproval`, the wire type behind [`PendingApprovalPrompt`])
/// — that is an existing, deliberate difference between the two wire
/// messages, not a gap introduced by this impl.
impl From<PendingApprovalEntry> for PendingApproval {
    fn from(p: PendingApprovalEntry) -> Self {
        Self {
            request_id: p.request_id,
            tool_name: p.tool_name,
            args_json: p.args_json,
            reason: p.reason,
            resolve_token: p.resolve_token,
        }
    }
}

/// Reusable handle for the control plane's `ApprovalService`.
///
/// The THIN human-in-the-loop path. Shares the `AgentService` endpoint — both
/// are served on one Connect port — so it is built from the same address.
#[derive(Clone)]
pub struct ApprovalDialer {
    client: Arc<ApprovalServiceClient<HttpClient>>,
}

impl ApprovalDialer {
    /// Build a dialer pointed at `addr` (expects `http://host:port`).
    ///
    /// # Errors
    /// Returns [`DialError::InvalidAddress`] if `addr` isn't a valid URI.
    pub fn new(addr: &str) -> Result<Self, DialError> {
        let uri = addr
            .parse::<http::Uri>()
            .map_err(|source| DialError::InvalidAddress {
                addr: addr.to_owned(),
                source,
            })?;
        let http = http_client_for(&uri)?;
        let client = ApprovalServiceClient::new(
            http,
            ClientConfig::new(uri).with_default_timeout(CONTROL_DIAL_TIMEOUT),
        );
        Ok(Self {
            client: Arc::new(client),
        })
    }

    /// Submit a human's decision for a pending approval. The decision is
    /// UNSIGNED — the control plane signs and persists it (THIN path) and
    /// returns the signature. Idempotent: answering an already-decided or
    /// unknown `request_id` returns `persisted: false`.
    ///
    /// When `approved_for_session` is true (and `approved` is true), the
    /// control plane remembers the decision for the paused turn's caller and
    /// auto-approves that caller's later identical, idempotent tool calls for
    /// the rest of the session ("approve & don't ask again"). Ignored on a
    /// denial.
    ///
    /// When `abort` is true (only meaningful with `approved = false`), this is
    /// an abort: the call is declined AND the caller should stop the turn (not
    /// re-drive it). A plain denial (`approved = false`, `abort = false`)
    /// declines the call but lets the turn continue. See [`ApprovalChoice`],
    /// which maps a button decision to these flags.
    ///
    /// `resolve_token` is the short-lived signed capability (`#787`) carried
    /// unmodified off the [`TurnEvent::ApprovalPending`] event or
    /// [`PendingApproval`] entry this decision answers — required: the
    /// control plane rejects a `Respond` whose token is missing, expired, or
    /// bound to a different request or conversation.
    ///
    /// `responder` is the identity of the human answering (`#68`), used to
    /// enforce a turn's required approver (`IngressDirective.required_approver`
    /// on the originating turn): Approve is refused unless `responder` matches.
    /// `None` still succeeds on a turn that names no required approver;
    /// Deny/Defer are unaffected — refusing is always safe regardless of who
    /// refuses. An edge that cannot supply caller identity on its respond
    /// path passes `None`.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error
    /// (including the control plane's rejection of an invalid
    /// `resolve_token`, or a `permission_denied` when `responder` doesn't
    /// match the turn's required approver).
    #[allow(clippy::too_many_arguments)] // each is a distinct field of the decision
    pub async fn respond(
        &self,
        request_id: &str,
        choice: ApprovalChoice,
        reason: &str,
        conversation_id: &str,
        modified_args_json: &str,
        injected_context: &str,
        resolve_token: &str,
        responder: Option<ExternalIdentity>,
    ) -> Result<ApprovalOutcome, DialError> {
        use polyc_proto::proto::polychrome::approval::v1::{
            Approve, Defer, Deny, approval_response_request::Decision,
        };
        // Map the choice into the structured `oneof` (#67). An approval carries
        // the approver's optional edit + injected context; a denial carries its
        // reason + abort hint; a defer ("send back") carries only its reason.
        let decision = if choice.is_defer() {
            Decision::Defer(Box::new(Defer {
                reason: reason.to_owned(),
                __buffa_unknown_fields: buffa::UnknownFields::default(),
            }))
        } else if choice.approved() {
            Decision::Approve(Box::new(Approve {
                modified_args_json: modified_args_json.to_owned(),
                injected_context: injected_context.to_owned(),
                reason: reason.to_owned(),
                approved_for_session: choice.approved_for_session(),
                __buffa_unknown_fields: buffa::UnknownFields::default(),
            }))
        } else {
            Decision::Deny(Box::new(Deny {
                reason: reason.to_owned(),
                abort: choice.is_abort(),
                __buffa_unknown_fields: buffa::UnknownFields::default(),
            }))
        };
        let request = ApprovalResponseRequest {
            request_id: request_id.to_owned(),
            conversation_id: conversation_id.to_owned(),
            decision: Some(decision),
            resolve_token: resolve_token.to_owned(),
            responder: responder.map_or_else(buffa::MessageField::none, buffa::MessageField::some),
            ..Default::default()
        };
        let reply = self
            .client
            .respond_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(reply.into())
    }

    /// List the conversation's outstanding approvals (a request with no later
    /// response). An edge calls this to recover `request_id`(s) it must prompt
    /// on after losing the streamed `ApprovalPending` event — turning a silent
    /// hang into a recoverable state. Read-only and idempotent.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error.
    pub async fn list_pending(
        &self,
        conversation_id: &str,
    ) -> Result<Vec<PendingApproval>, DialError> {
        let mut pending = Vec::new();
        let mut page_token = String::new();
        loop {
            let request = ListPendingRequest {
                conversation_id: conversation_id.to_owned(),
                page_token: page_token.clone(),
                ..Default::default()
            };
            let reply = self
                .client
                .list_pending_with_options(request, traced_options())
                .await?
                .into_owned();
            pending.extend(reply.pending.into_iter().map(PendingApproval::from));
            if reply.next_page_token.is_empty() {
                break;
            }
            page_token = reply.next_page_token;
        }
        Ok(pending)
    }

    /// Remove outside content from a conversation (`#590`) so its web and
    /// outside access recover. Admin-gated server-side; the control plane
    /// verifies `actor` holds the admin role, appends the signed removal
    /// record, and reports which journal positions left the working context.
    ///
    /// `positions` names specific entries; `all_quarantined` removes every
    /// entry currently carrying outside content (`positions` is then
    /// ignored). `source_only` limits the removal to the named entries — the
    /// default also removes what the agent produced after them, which is the
    /// safer posture when the content may have steered it.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error, a
    /// permission refusal, or an invalid position.
    pub async fn excise_taint(
        &self,
        conversation_id: &str,
        positions: &[u64],
        all_quarantined: bool,
        source_only: bool,
        reason: &str,
        actor: polyc_proto::proto::polychrome::persona::v1::ExternalIdentity,
    ) -> Result<ExcisionOutcome, DialError> {
        use polyc_proto::proto::polychrome::approval::v1::ExciseTaintRequest;
        let request = ExciseTaintRequest {
            conversation_id: conversation_id.to_owned(),
            positions: positions.to_vec(),
            all_quarantined,
            source_only,
            reason: reason.to_owned(),
            actor: buffa::MessageField::some(actor),
            ..Default::default()
        };
        let reply = self
            .client
            .excise_taint_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(reply.into())
    }

    /// Replay a recorded conversation against its committed event log (`#690`):
    /// re-execute its committed turns in process — no live model, no live tools,
    /// nothing sent or spent again — and return a per-turn verdict. Read-only:
    /// the control plane appends nothing and takes no writer lease, so it is safe
    /// to run on production data any number of times.
    ///
    /// Admin-gated (`#694`): the control plane verifies `actor` holds the admin
    /// role — the same gate `excise_taint` applies — before it reads or replays
    /// anything, so a non-admin (or absent) actor is refused.
    ///
    /// `from`/`to` bound the 0-based committed-turn ordinals (inclusive); `None`
    /// means the ends. A set `over` selects what-if mode (fork one recorded step
    /// and report where the conversation diverges); `None` is a plain verify
    /// (assert every turn reproduces its record).
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error, or a
    /// permission refusal when `actor` is not an admin.
    pub async fn replay_conversation(
        &self,
        conversation_id: &str,
        from: Option<usize>,
        to: Option<usize>,
        over: Option<ReplayOverrideSpec>,
        actor: polyc_proto::proto::polychrome::persona::v1::ExternalIdentity,
    ) -> Result<ReplayReport, DialError> {
        use polyc_proto::proto::polychrome::approval::v1::{
            ReplayConversationRequest, ReplayOverride,
        };
        let override_msg = over.map(ReplayOverride::from);
        // An absent bound is the `-1` sentinel; the control plane maps a negative
        // ordinal to "the ends".
        let to_bound = |v: Option<usize>| v.and_then(|n| i64::try_from(n).ok()).unwrap_or(-1);
        let request = ReplayConversationRequest {
            conversation_id: conversation_id.to_owned(),
            from: to_bound(from),
            to: to_bound(to),
            r#override: override_msg
                .map_or_else(buffa::MessageField::none, buffa::MessageField::some),
            actor: buffa::MessageField::some(actor),
            ..Default::default()
        };
        let reply = self
            .client
            .replay_conversation_with_options(request, traced_options())
            .await?
            .into_owned();
        let turns = reply
            .turns
            .into_iter()
            .map(ReplayTurnVerdict::from)
            .collect();
        Ok(ReplayReport {
            turns,
            all_match: reply.all_match,
        })
    }

    /// Verify a conversation's tamper-evidence (`#799`): replay its event log
    /// and check every signed MMR root recorded along the way against a
    /// freshly rebuilt tree. Read-only — appends nothing.
    ///
    /// Admin-gated server-side, the same gate `excise_taint` uses.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error, or a
    /// permission refusal when `actor` is not an admin.
    pub async fn verify_conversation(
        &self,
        conversation_id: &str,
        actor: polyc_proto::proto::polychrome::persona::v1::ExternalIdentity,
    ) -> Result<VerificationOutcome, DialError> {
        use polyc_proto::proto::polychrome::approval::v1::VerifyConversationRequest;
        let request = VerifyConversationRequest {
            conversation_id: conversation_id.to_owned(),
            actor: buffa::MessageField::some(actor),
            ..Default::default()
        };
        let reply = self
            .client
            .verify_conversation_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(reply.into())
    }

    /// Repair a conversation's event log (`#799`, the `conversation repair`
    /// quarantine verb): replay every position independently so one
    /// corrupted item cannot block the rest, then rewrite the partition
    /// retaining only what decoded. A partition with nothing corrupted is a
    /// no-op (empty quarantine list).
    ///
    /// Admin-gated server-side, the same gate `excise_taint` uses.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error, or a
    /// permission refusal when `actor` is not an admin.
    pub async fn repair_conversation(
        &self,
        conversation_id: &str,
        actor: polyc_proto::proto::polychrome::persona::v1::ExternalIdentity,
    ) -> Result<Vec<u64>, DialError> {
        use polyc_proto::proto::polychrome::approval::v1::RepairConversationRequest;
        let request = RepairConversationRequest {
            conversation_id: conversation_id.to_owned(),
            actor: buffa::MessageField::some(actor),
            ..Default::default()
        };
        let reply = self
            .client
            .repair_conversation_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(reply.quarantined_positions)
    }
}

/// One counterfactual override for a what-if [`ApprovalDialer::replay_conversation`].
///
/// Mirrors the control plane's replay override so a `conversation replay
/// --what-if` command names an override without depending on `polyc-proto`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReplayOverrideSpec {
    /// Replace turn `turn`'s first recorded completion text.
    Completion {
        /// 0-based committed-turn ordinal to fork at.
        turn: u32,
        /// The counterfactual completion text.
        text: String,
    },
    /// Replace turn `turn`'s `index`-th recorded tool result.
    ToolResult {
        /// 0-based committed-turn ordinal to fork at.
        turn: u32,
        /// Which recorded tool result (in call order) to replace.
        index: u32,
        /// The counterfactual tool result JSON.
        result_json: String,
    },
}

/// Every field named explicitly — no `..Default::default()` spread on any of
/// the three wire messages this builds — so a field added to any of them
/// without updating this impl fails to compile instead of silently not
/// riding the wire.
impl From<ReplayOverrideSpec> for polyc_proto::proto::polychrome::approval::v1::ReplayOverride {
    fn from(spec: ReplayOverrideSpec) -> Self {
        use polyc_proto::proto::polychrome::approval::v1::{
            ReplayCompletionOverride, ReplayToolResultOverride, replay_override::Kind,
        };
        let kind = match spec {
            ReplayOverrideSpec::Completion { turn, text } => {
                Kind::Completion(Box::new(ReplayCompletionOverride {
                    turn,
                    text,
                    __buffa_unknown_fields: buffa::UnknownFields::default(),
                }))
            }
            ReplayOverrideSpec::ToolResult {
                turn,
                index,
                result_json,
            } => Kind::ToolResult(Box::new(ReplayToolResultOverride {
                turn,
                index,
                result_json,
                __buffa_unknown_fields: buffa::UnknownFields::default(),
            })),
        };
        Self {
            kind: Some(kind),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

/// How one replayed turn compared against its record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReplayTurnOutcome {
    /// Every compared field reproduced the record.
    Match,
    /// The turn diverged from the record (verify) or forked from it (what-if) at
    /// `field`, with a human-readable `detail`.
    Diverged {
        /// The first field that differs (e.g. `"messages"`, `"usage"`, `"stop"`).
        field: String,
        /// The divergence explanation.
        detail: String,
    },
    /// The turn's recorded inputs are incomplete (excised or malformed), so it
    /// cannot be faithfully reproduced — reported, never passed.
    Unreplayable {
        /// Why the turn could not be reproduced.
        reason: String,
    },
}

/// One turn's replay verdict, as [`ApprovalDialer::replay_conversation`] returns it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReplayTurnVerdict {
    /// The turn's 0-based committed ordinal.
    pub turn_index: u32,
    /// How the turn compared against its record.
    pub outcome: ReplayTurnOutcome,
}

/// Total over the wire `ReplayOutcome` enum — an unknown/unspecified value
/// maps to [`ReplayTurnOutcome::Unreplayable`] rather than being dropped, so
/// this is a `From`, not a `TryFrom`.
impl From<polyc_proto::proto::polychrome::approval::v1::ReplayTurnVerdict> for ReplayTurnVerdict {
    fn from(v: polyc_proto::proto::polychrome::approval::v1::ReplayTurnVerdict) -> Self {
        use polyc_proto::proto::polychrome::approval::v1::ReplayOutcome;
        let outcome = match v.outcome.as_known() {
            Some(ReplayOutcome::Match) => ReplayTurnOutcome::Match,
            Some(ReplayOutcome::Diverged) => ReplayTurnOutcome::Diverged {
                field: v.field,
                detail: v.detail,
            },
            Some(ReplayOutcome::Unreplayable) => {
                ReplayTurnOutcome::Unreplayable { reason: v.detail }
            }
            Some(ReplayOutcome::Unspecified) | None => ReplayTurnOutcome::Unreplayable {
                reason: "the control plane returned an unknown replay outcome".to_owned(),
            },
        };
        Self {
            turn_index: v.turn_index,
            outcome,
        }
    }
}

/// The whole-conversation replay report a `conversation replay` command renders.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReplayReport {
    /// Per-turn verdicts, in recorded order.
    pub turns: Vec<ReplayTurnVerdict>,
    /// True only when every replayed turn matched its record (the verify pass);
    /// false on any divergence or unreplayable turn.
    pub all_match: bool,
}

/// Result of an [`ApprovalDialer::excise_taint`] call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExcisionOutcome {
    /// Whether a removal record was durably appended (`false` = idempotent
    /// no-op: nothing was left to remove).
    pub persisted: bool,
    /// The journal positions that left the working context, after scope
    /// expansion.
    pub excised_positions: Vec<u64>,
    /// Hex signature over the removal record.
    pub signature_hex: String,
    /// Hex public key of the signer.
    pub signed_by_hex: String,
}

impl From<polyc_proto::proto::polychrome::approval::v1::ExciseTaintReply> for ExcisionOutcome {
    fn from(reply: polyc_proto::proto::polychrome::approval::v1::ExciseTaintReply) -> Self {
        Self {
            persisted: reply.persisted,
            excised_positions: reply.excised_positions,
            signature_hex: reply.signature_hex,
            signed_by_hex: reply.signed_by_hex,
        }
    }
}

/// Result of an [`ApprovalDialer::verify_conversation`] call (`#799`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerificationOutcome {
    /// Whether every signed root in the log matched what replay recomputed.
    pub verified: bool,
    /// Human-readable detail on the first violation found; empty when
    /// `verified` is true.
    pub violation: String,
    /// Number of events the (successful) replay read.
    pub event_count: u64,
}

impl From<polyc_proto::proto::polychrome::approval::v1::VerifyConversationReply>
    for VerificationOutcome
{
    fn from(reply: polyc_proto::proto::polychrome::approval::v1::VerifyConversationReply) -> Self {
        Self {
            verified: reply.verified,
            violation: reply.violation,
            event_count: reply.event_count,
        }
    }
}

/// A freshly minted link-ceremony challenge: the code an edge must deliver
/// privately to the requesting user, plus its absolute expiry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StartedLink {
    /// The single-use 6-digit code (a credential — never log or display it
    /// outside a private channel the user owns).
    pub code: String,
    /// Unix-ms after which the code is refused.
    pub expires_at_ms: u64,
    /// The persona the code is bound to.
    pub persona_id: String,
}

impl From<polyc_proto::proto::polychrome::persona::v1::StartLinkReply> for StartedLink {
    fn from(reply: polyc_proto::proto::polychrome::persona::v1::StartLinkReply) -> Self {
        Self {
            code: reply.code,
            expires_at_ms: reply.expires_at_ms,
            persona_id: reply.persona_id,
        }
    }
}

impl From<polyc_proto::proto::polychrome::persona::v1::AdminInviteReply> for StartedLink {
    fn from(reply: polyc_proto::proto::polychrome::persona::v1::AdminInviteReply) -> Self {
        Self {
            code: reply.code,
            expires_at_ms: reply.expires_at_ms,
            persona_id: reply.persona_id,
        }
    }
}

/// A freshly minted deep-link token: the opaque value an edge embeds in a
/// platform URL for a no-typing ceremony, plus its absolute expiry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StartedDeepLink {
    /// The single-use, high-entropy token (a credential — only ever placed in
    /// a deep-link URL delivered to a private channel the user owns).
    pub token: String,
    /// Unix-ms after which the token is refused.
    pub expires_at_ms: u64,
    /// The persona the token is bound to.
    pub persona_id: String,
}

impl From<polyc_proto::proto::polychrome::persona::v1::StartDeepLinkReply> for StartedDeepLink {
    fn from(reply: polyc_proto::proto::polychrome::persona::v1::StartDeepLinkReply) -> Self {
        Self {
            token: reply.token,
            expires_at_ms: reply.expires_at_ms,
            persona_id: reply.persona_id,
        }
    }
}

/// The outcome of completing a link ceremony, in edge-renderable terms.
///
/// `InvalidCode` and `Expired` are deliberately fused into one variant: the
/// proto contract is that edges present them identically so a guesser cannot
/// learn whether a code was ever valid. The distinction stays in the control
/// plane's logs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LinkCeremony {
    /// The identity is now bound to the persona (directly or by merge).
    Linked {
        /// The surviving persona id.
        persona_id: String,
    },
    /// The identity already resolved to that persona; the code was consumed.
    AlreadyLinked {
        /// The persona id.
        persona_id: String,
    },
    /// No usable code (never minted, already consumed, or expired). Rendered
    /// identically to the user.
    InvalidOrExpired,
    /// The completing identity is locked out after repeated failures (or the
    /// deployment-wide backstop tripped). Rendered distinctly: "wait".
    Throttled,
    /// An unexpected/unspecified outcome — the edge should surface a generic
    /// failure rather than claim success.
    Failed,
}

impl LinkCeremony {
    /// The user-facing message for this outcome, shared by every edge.
    ///
    /// `InvalidCode` and `Expired` are fused into one variant upstream (so no
    /// edge can distinguish them — no oracle for a guesser); centralizing the
    /// rendering here keeps that security-relevant wording identical across
    /// surfaces. Channel-neutral phrasing; an edge that needs surface-specific
    /// text can still match the variant itself.
    #[must_use]
    pub const fn user_message(&self) -> &'static str {
        match self {
            Self::Linked { .. } => {
                "✅ Linked — this account now shares one Polychrome persona with your other channels."
            }
            Self::AlreadyLinked { .. } => {
                "✅ Already linked — this account was already on that persona."
            }
            Self::InvalidOrExpired => {
                "That link is invalid or expired. Start a fresh one from your other channel and try again."
            }
            Self::Throttled => "Too many attempts — wait a few minutes, then try again.",
            Self::Failed => "That link failed to complete. Start a fresh one and try again.",
        }
    }
}

/// The user-facing message for an admin-invite dial failure, shared by every
/// edge.
///
/// Centralizes the wording so the Slack and Telegram invite handlers can't
/// drift on copy for the identical state (the CLAUDE.md "route through a
/// shared helper" rule). Permission-denied maps to [`ADMIN_ONLY_INVITE`]; a
/// surface where echoing a refusal is unsafe (a group chat, where it would
/// let a non-admin make the bot speak / probe who is an admin) can suppress
/// the message itself rather than call this.
#[must_use]
pub const fn invite_error_message(err: &DialError) -> &'static str {
    match err.code() {
        Some(ErrorCode::PermissionDenied) => ADMIN_ONLY_INVITE,
        Some(ErrorCode::ResourceExhausted) => {
            "That's a lot of invites in a row — wait a couple of minutes, then try again."
        }
        _ => "I couldn't create the invite right now — try again in a moment.",
    }
}

/// The "only admins can invite" refusal copy, shared across edges.
pub const ADMIN_ONLY_INVITE: &str = "Only admins can send invites.";

/// User-facing copy for a [`PersonaDialer::set_incognito`] failure (`#796`),
/// shared across edges so the toggle reads identically wherever it's
/// reachable from.
#[must_use]
pub const fn incognito_error_message(err: &DialError) -> &'static str {
    match err.code() {
        Some(ErrorCode::PermissionDenied) => {
            "I couldn't toggle incognito — that only works for a conversation you're part of."
        }
        _ => "I couldn't toggle incognito — try again.",
    }
}

/// Reusable handle for the control plane's `PersonaService`.
///
/// The verified identity-linking ceremonies. Shares the `AgentService`
/// endpoint — all three services are served on one internal Connect port —
/// so it is built from the same address.
#[derive(Clone)]
pub struct PersonaDialer {
    client: Arc<PersonaServiceClient<HttpClient>>,
}

impl PersonaDialer {
    /// Build a dialer pointed at `addr` (expects `http://host:port`).
    ///
    /// # Errors
    /// Returns [`DialError::InvalidAddress`] if `addr` isn't a valid URI.
    pub fn new(addr: &str) -> Result<Self, DialError> {
        let uri = addr
            .parse::<http::Uri>()
            .map_err(|source| DialError::InvalidAddress {
                addr: addr.to_owned(),
                source,
            })?;
        let http = http_client_for(&uri)?;
        let client = PersonaServiceClient::new(
            http,
            ClientConfig::new(uri).with_default_timeout(CONTROL_DIAL_TIMEOUT),
        );
        Ok(Self {
            client: Arc::new(client),
        })
    }

    /// Mint a single-use link-ceremony code bound to `identity`'s persona
    /// (provisioning one on first contact). The returned [`StartedLink::code`]
    /// is a credential the caller must deliver only to a private channel the
    /// user owns.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error.
    pub async fn start_link(&self, identity: ExternalIdentity) -> Result<StartedLink, DialError> {
        let request = StartLinkRequest {
            identity: buffa::MessageField::some(identity),
            ..Default::default()
        };
        let reply = self
            .client
            .start_link_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(reply.into())
    }

    /// Mint a high-entropy deep-link token bound to `identity`'s persona, for
    /// a no-typing ceremony (the caller embeds [`StartedDeepLink::token`] in a
    /// platform URL like `https://t.me/<bot>?start=<token>`). The token is a
    /// credential — deliver the URL only to a private channel the user owns.
    /// Completed via [`Self::complete_link`] from the target platform.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error.
    pub async fn start_deeplink(
        &self,
        identity: ExternalIdentity,
    ) -> Result<StartedDeepLink, DialError> {
        let request = StartDeepLinkRequest {
            identity: buffa::MessageField::some(identity),
            ..Default::default()
        };
        let reply = self
            .client
            .start_deep_link_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(reply.into())
    }

    /// Admin-gated: mint an invite code for a TARGET identity distinct from
    /// the acting admin. The code binds to the target — only the target can
    /// redeem it — and is a credential: deliver it only to a private channel
    /// the TARGET owns, never back through the admin's shared surfaces.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error; a
    /// non-admin actor surfaces as `permission_denied`.
    pub async fn admin_invite(
        &self,
        actor: ExternalIdentity,
        target: ExternalIdentity,
    ) -> Result<StartedLink, DialError> {
        let request = AdminInviteRequest {
            actor: buffa::MessageField::some(actor),
            target: buffa::MessageField::some(target),
            ..Default::default()
        };
        let reply = self
            .client
            .admin_invite_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(reply.into())
    }

    /// Toggle incognito for a conversation (`#796`): suppresses memory
    /// extraction from here on when `on`, clears the suppression when not.
    /// The control plane authorizes `actor` — an admin may toggle any
    /// conversation, anyone else only one they are a caller or participant
    /// of — so a non-admin's own conversation is reachable through this same
    /// call; an unrelated conversation surfaces as `permission_denied`.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error,
    /// including a `permission_denied` refusal.
    pub async fn set_incognito(
        &self,
        actor: ExternalIdentity,
        conversation_id: &str,
        on: bool,
    ) -> Result<bool, DialError> {
        let request = SetIncognitoRequest {
            actor: buffa::MessageField::some(actor),
            conversation_id: conversation_id.to_owned(),
            on,
            ..Default::default()
        };
        let reply = self
            .client
            .set_incognito_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(reply.on)
    }

    /// Deterministic workspace-email auto-link: bind `identity` to the
    /// persona already holding a ceremony-verified email matching
    /// `asserted_email`. The email must come from the PLATFORM API (e.g.
    /// Slack `users.info`) — never from user-typed text. Returns whether a
    /// link happened so the edge can notify the user ("if this wasn't
    /// you…"); halting outcomes come back as `Ok(None)`.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error.
    pub async fn auto_link(
        &self,
        identity: ExternalIdentity,
        asserted_email: &str,
        basis: &str,
    ) -> Result<Option<String>, DialError> {
        let request = AutoLinkRequest {
            identity: buffa::MessageField::some(identity),
            asserted_email: asserted_email.to_owned(),
            basis: basis.to_owned(),
            ..Default::default()
        };
        let reply = self
            .client
            .auto_link_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(match reply.outcome.as_known() {
            Some(AutoLinkOutcome::Linked) => Some(reply.persona_id),
            _ => None,
        })
    }

    /// Consume `code` from the channel being claimed, binding `identity` to
    /// the minting persona (merging `identity`'s prior persona if it had one).
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error.
    pub async fn complete_link(
        &self,
        code: &str,
        identity: ExternalIdentity,
    ) -> Result<LinkCeremony, DialError> {
        let request = CompleteLinkRequest {
            code: code.to_owned(),
            identity: buffa::MessageField::some(identity),
            ..Default::default()
        };
        let reply = self
            .client
            .complete_link_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(match reply.outcome.as_known() {
            Some(LinkOutcome::Linked) => LinkCeremony::Linked {
                persona_id: reply.persona_id,
            },
            Some(LinkOutcome::AlreadyLinked) => LinkCeremony::AlreadyLinked {
                persona_id: reply.persona_id,
            },
            // Fused on purpose — see `LinkCeremony::InvalidOrExpired`.
            Some(LinkOutcome::InvalidCode | LinkOutcome::Expired) => LinkCeremony::InvalidOrExpired,
            Some(LinkOutcome::Throttled) => LinkCeremony::Throttled,
            Some(LinkOutcome::Unspecified) | None => LinkCeremony::Failed,
        })
    }

    /// Read-only: the profile the `identity` resolves to, as an edge-friendly
    /// [`PersonaView`]. Returns an all-empty view for an identity not yet in
    /// the directory; **never provisions** a persona.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error.
    pub async fn describe(&self, identity: ExternalIdentity) -> Result<PersonaView, DialError> {
        let request = DescribeRequest {
            identity: buffa::MessageField::some(identity),
            ..Default::default()
        };
        let reply = self
            .client
            .describe_with_options(request, traced_options())
            .await?
            .into_owned();
        // Unknown identity → empty profile → an all-default view (the
        // not-yet-claimed dashboard state).
        let Some(profile) = reply.profile.into_option() else {
            return Ok(PersonaView {
                persona_id: reply.persona_id,
                ..Default::default()
            });
        };
        Ok(PersonaView {
            persona_id: reply.persona_id,
            status: profile.status,
            identities: profile
                .identities
                .into_iter()
                .map(LinkedIdentity::from)
                .collect(),
        })
    }
}

/// One external identity linked to a persona, as the dashboard renders it
/// (provider · display name · id).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkedIdentity {
    /// Edge namespace ("slack", "telegram", …).
    pub provider: String,
    /// The provider-native stable id.
    pub external_id: String,
    /// Display name as last observed (presentation only).
    pub display_name: String,
}

/// Deliberate subset projection: the dashboard doesn't render `scope`, the
/// one field the wire `ExternalIdentity` has beyond these three.
impl From<ExternalIdentity> for LinkedIdentity {
    fn from(id: ExternalIdentity) -> Self {
        Self {
            provider: id.provider,
            external_id: id.external_id,
            display_name: id.display_name,
        }
    }
}

/// An edge-friendly read of a persona, for surfaces like the App Home
/// dashboard. Every field is empty when the queried identity is not in the
/// directory (a not-yet-claimed user).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PersonaView {
    /// The persona id; empty when the identity is unknown.
    pub persona_id: String,
    /// "provisional" | "linked" | "merged"; empty when unknown.
    pub status: String,
    /// Every identity currently linked to the persona.
    pub identities: Vec<LinkedIdentity>,
}

/// A turn-input message, re-exported so callers can build attributed
/// multi-party input for [`AgentDialer::run_turn_streaming_messages`] without
/// depending on `polyc-proto`.
pub use polyc_proto::proto::polychrome::agent::v1::Message as TurnMessage;
/// The attributed transcript line type the participation gate consumes.
/// Re-exported so callers build requests without importing `polyc-proto`.
pub use polyc_proto::proto::polychrome::agent::v1::ParticipantMessage as GateMessage;
/// A settled inbound payment receipt, re-exported so the public-edge layer can
/// thread it into [`AgentDialer::run_turn_streaming_messages_with`]
/// without depending on `polyc-proto` directly.
pub use polyc_proto::proto::polychrome::agent::v1::PaymentReceipt;

/// The external identity of a human observed at an edge (re-exported wire
/// type, shared with the persona store records): the per-edge `EdgeAdapter`
/// mapping produces these and the control plane resolves them to durable
/// personas.
pub use polyc_proto::proto::polychrome::persona::v1::ExternalIdentity;

/// The Connect error-code enum, re-exported so edges can branch on
/// [`DialError::code`] (e.g. render `permission_denied` differently from a
/// transient failure) without depending on `connectrpc` directly.
pub use connectrpc::ErrorCode;

/// Caller attribution for one turn.
///
/// Carries the identity whose message triggered the turn (`caller`) and any
/// other humans whose messages entered the turn's input (`participants`).
/// Edges without caller identity pass the default.
#[derive(Debug, Clone, Default)]
pub struct Attribution {
    /// The identity whose message triggered the turn.
    pub caller: Option<ExternalIdentity>,
    /// Other humans whose messages entered this turn's input.
    pub participants: Vec<ExternalIdentity>,
}

/// Build an attributed user-role turn message rendered as `"<speaker>: text"`,
/// so the model sees who said what in a multi-party thread.
#[must_use]
pub fn attributed_message(speaker: &str, text: &str) -> TurnMessage {
    text_message("user", &format!("{speaker}: {text}"))
}

/// Build a plain user-role turn message (no speaker attribution) — used for
/// 1:1 DMs where there is only one human in the conversation.
#[must_use]
pub fn user_message(text: &str) -> TurnMessage {
    text_message("user", text)
}

/// Build the documented **readable** namespaced conversation id,
/// `"{namespace}:{native_id}"`.
///
/// Every edge derives [`AgentRequest::conversation_id`] from its native unit
/// (a thread, a ticket, an issue, a session). The convention is a namespace
/// prefix that names the edge family, followed by the edge's own stable handle
/// for the conversation — e.g. `mail:{message-id}`, `web:{session-uuid}`,
/// `mcp:{caller-id}`. The id is opaque to the orchestration core (it is the
/// event-log partition key, `conv-{id}`); only the *format* is a shared
/// convention so edges stay consistent and ids are greppable.
///
/// Edges whose native coordinate is unwieldy or sensitive — many chat
/// platforms — should instead use [`hashed_conversation_id`], which collapses
/// the coordinate into a fixed-length opaque `UUIDv5` under a pinned namespace.
#[must_use]
pub fn namespaced_id(namespace: &str, native_id: &str) -> String {
    format!("{namespace}:{native_id}")
}

/// Build the conversation-partition id of one routine enrollment:
/// `"cron:{routine}:{persona_id}"`.
///
/// An enrollment keeps its state (the enrollment event, the signed grant, later
/// revocations and nudges) in its own event-log partition, distinct from any
/// chat conversation. The id pairs the routine name with the enrolling
/// principal (a persona id), so every principal who joins a routine gets a
/// separate partition and one principal's grant state never bleeds into
/// another's. The `cron:` family prefix marks it as an unattended-routine
/// partition rather than an edge conversation.
///
/// Routine names are DNS-1123 and persona ids are opaque flat ids, so neither
/// carries a `:`; the storage layer maps the `:` separators to `_` the same way
/// it does for every namespaced id (see the event-log host's partition
/// sanitizer), so the readable form here round-trips to one legal on-disk
/// partition. This is the shared contract the enrollment ceremony (#621) writes
/// and the fan-out (#622) reads — both derive the partition through this one
/// function so the two can never disagree on where an enrollment lives.
#[must_use]
pub fn enrollment_conversation_id(routine: &str, persona_id: &str) -> String {
    debug_assert!(
        !routine.contains(':'),
        "routine name `{routine}` must be DNS-1123-shaped (no ':'), enforced by the CRD name \
         grammar Kubernetes applies to `Routine.metadata.name`"
    );
    debug_assert!(
        !persona_id.contains(':'),
        "persona id `{persona_id}` must be a bare UUID (no ':'), minted by \
         `polyc_persona::new_provisional` as `uuid::Uuid::now_v7().to_string()`"
    );
    format!("cron:{routine}:{persona_id}")
}

/// Parse an enrollment conversation id back into its `(routine, persona)`, the
/// inverse of [`enrollment_conversation_id`].
///
/// Returns `Some` only for the three-segment enrollment form
/// `cron:{routine}:{persona}`; a plain cron conversation id (`cron:{id}`, two
/// segments) returns `None`, so the two are never confused. Routine names are
/// DNS-1123 and persona ids are UUIDs — neither carries a `:` — so the split is
/// unambiguous. This is how the control plane recognises that a conversation is
/// a routine enrollment (to bind its `Conversation` CR to the routine's agent
/// and connector, #622) rather than an ordinary cron job.
#[must_use]
pub fn parse_enrollment_conversation_id(conversation_id: &str) -> Option<(&str, &str)> {
    let rest = conversation_id.strip_prefix("cron:")?;
    let (routine, persona) = rest.split_once(':')?;
    // Both halves must be non-empty, and the persona must itself be a leaf (no
    // further `:`); a well-formed id never has a fourth segment.
    if routine.is_empty() || persona.is_empty() || persona.contains(':') {
        return None;
    }
    Some((routine, persona))
}

/// Derive a stable, fixed-length conversation id by hashing `parts` into a
/// `UUIDv5` under a pinned `namespace`.
///
/// This is the "opaque hash" namespacing policy: a deterministic,
/// stateless-across-restarts id (no `native → id` table to keep) that is
/// globally unique enough to key the event-log partition. `parts` are joined
/// with `':'` before hashing, so a caller passing `["T1", "C1", "169…"]`
/// hashes exactly `"T1:C1:169…"`.
///
/// The pinned `namespace` UUID **must never change** for a given edge — every
/// existing conversation id for that edge depends on it. `polychrome-slack`
/// uses this policy (its `UUIDv5` over `(team, channel, thread_ts)`); new edges
/// pick their own frozen namespace.
#[must_use]
pub fn hashed_conversation_id(namespace: uuid::Uuid, parts: &[&str]) -> String {
    let joined = parts.join(":");
    uuid::Uuid::new_v5(&namespace, joined.as_bytes())
        .hyphenated()
        .to_string()
}

/// Collision-free variant of [`hashed_conversation_id`] for edges whose native
/// parts can themselves contain `':'` (e.g. an email `Message-ID`, a URL, a
/// path).
///
/// [`hashed_conversation_id`] joins parts with a bare `':'`, so `["a:b", "c"]`
/// and `["a", "b:c"]` both hash `"a:b:c"` and collide. This helper instead
/// **length-prefixes** each part (`"{len}:{part}"`), which is unambiguous
/// regardless of any `':'` inside a part — the length says exactly how many
/// bytes the part occupies, so distinct part boundaries always produce distinct
/// hash inputs. Use it for any edge whose coordinate fields are not guaranteed
/// `':'`-free.
///
/// Distinct from [`hashed_conversation_id`] precisely because the framing
/// differs; the two do not agree for the same `parts`.
#[must_use]
pub fn framed_conversation_id(namespace: uuid::Uuid, parts: &[&str]) -> String {
    let mut framed = String::new();
    for p in parts {
        framed.push_str(&p.len().to_string());
        framed.push(':');
        framed.push_str(p);
    }
    uuid::Uuid::new_v5(&namespace, framed.as_bytes())
        .hyphenated()
        .to_string()
}

/// Every field named explicitly — no `..Default::default()` spread — so a
/// field added to `WireIngressDirective` without updating this impl fails to
/// compile instead of silently not riding the wire. `IngressDirective` is a
/// fail-closed policy envelope (`#68`): a dropped `required_approver` or
/// `budget_cap` here is a fail-open bug, not just data loss.
impl From<IngressDirective> for WireIngressDirective {
    fn from(directive: IngressDirective) -> Self {
        Self {
            budget_cap: directive.budget_cap.unwrap_or_default(),
            priority: directive.priority.map_or_else(
                || buffa::EnumValue::from(Priority::PRIORITY_UNSPECIFIED),
                buffa::EnumValue::from,
            ),
            required_approver: directive
                .required_approver
                .map_or_else(buffa::MessageField::none, buffa::MessageField::some),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        }
    }
}

/// Convert the SDK-facing [`IngressDirective`] into the wire
/// `polychrome.agent.v1.IngressDirective`, `None` for an empty directive
/// (`#68`) — so an edge that sets no policy sends the field unset, matching
/// [`IngressDirective::is_empty`]'s "byte-for-byte unaffected" contract.
fn wire_ingress_directive(
    directive: IngressDirective,
) -> buffa::MessageField<WireIngressDirective> {
    if directive.is_empty() {
        return buffa::MessageField::none();
    }
    buffa::MessageField::some(directive.into())
}

/// Build the single [`AgentRequest`] that opens an `AgentService.connect`
/// stream. Shared by [`AgentDialer::run_turn`] and
/// [`AgentDialer::run_turn_streaming`] so the two paths can't drift.
// One builder carries every field an `AgentStart` can, so the buffered and
// streaming paths can't drift on what a request looks like; that is inherently
// wide, and threading these through a params struct would only move the same
// fields behind one more indirection.
#[allow(clippy::too_many_arguments)]
fn build_request(
    conversation_id: &str,
    exec_id: &str,
    messages: Vec<Message>,
    payment_receipt: Option<PaymentReceipt>,
    attribution: Attribution,
    ephemeral_history: bool,
    ingress_directive: IngressDirective,
    occurrence: &str,
) -> AgentRequest {
    AgentRequest {
        conversation_id: conversation_id.to_owned(),
        exec_id: exec_id.to_owned(),
        start: buffa::MessageField::some(AgentStart {
            agent_id: String::new(),
            agent_config: Vec::new(),
            messages,
            payment_receipt: payment_receipt
                .map_or_else(buffa::MessageField::none, buffa::MessageField::some),
            caller: attribution
                .caller
                .map_or_else(buffa::MessageField::none, buffa::MessageField::some),
            participants: attribution.participants,
            // #843: a routine fire declares ephemeral history so each firing
            // starts the model on an empty transcript; every other edge leaves
            // this false (persistent).
            ephemeral_history,
            ingress_directive: wire_ingress_directive(ingress_directive),
            // #1103: the scheduled tick that produced this turn, when a routine's
            // cron binding fired it. Empty for every other caller — a chat turn
            // or a manual trigger send — so the field rides the wire unset and
            // never dedups.
            occurrence: occurrence.to_owned(),
            ..Default::default()
        }),
        ..Default::default()
    }
}

/// Project a terminal [`AgentEnd`] into the [`TurnEvent`]s a live surface sees
/// at end-of-turn: one [`TurnEvent::ApprovalPending`] per paused tool call,
/// then a [`TurnEvent::HandoffStarted`] if the turn delegated to a sub-agent,
/// then one [`TurnEvent::InviteDelivery`] per admin invite minted this turn,
/// then a [`TurnEvent::WalletLinkPrompt`] if a paid call needed a linked
/// wallet, then a [`TurnEvent::TurnFailed`] if the turn ended durably failed,
/// then the terminal [`TurnEvent::Done`].
///
/// Pure (no I/O) so the End-arm mapping can be unit-tested without a live
/// stream, mirroring [`message_to_event`] for the Outputs arm.
fn events_from_end(end: AgentEnd) -> Vec<TurnEvent> {
    let mut events: Vec<TurnEvent> = end
        .pending_approvals
        .into_iter()
        .map(PendingApprovalPrompt::from)
        .map(TurnEvent::from)
        .collect();
    if let Some(h) = end.handoff.into_option() {
        events.push(TurnEvent::HandoffStarted {
            child_agent_id: h.child_agent_id,
            reason: h.reason,
        });
    }
    // Each minted invite becomes a delivery event for the edge to act on. The
    // code rides only here (control plane → edge); the edge routes it to the
    // target's DM and nowhere else.
    for d in end.invite_deliveries {
        events.push(TurnEvent::InviteDelivery {
            target_user_id: d.target_user_id,
            code: d.code,
            inviter_display: d.inviter_display,
        });
    }
    // A paid tool call this turn needed a linked wallet (`#519`). The wire
    // carries only the URL (empty = unknown); a blank/whitespace-only value
    // maps to `None` so the edge renders the no-button, admin-pointer card.
    if let Some(prompt) = end.wallet_link_prompt.into_option() {
        let link_url = (!prompt.link_url.trim().is_empty()).then_some(prompt.link_url);
        events.push(TurnEvent::WalletLinkPrompt { link_url });
    }
    // `persona_credential_setup` minted a fresh enrollment link this turn
    // (PRD #767). Same blank-collapses-to-`None` treatment as the wallet-link
    // prompt above, though in practice the control plane never sets this
    // field with an empty URL (see `PersonaCredentialPrompt`'s wire doc).
    if let Some(prompt) = end.persona_credential_prompt.into_option() {
        let link_url = (!prompt.link_url.trim().is_empty()).then_some(prompt.link_url);
        events.push(TurnEvent::PersonaCredentialPrompt { link_url });
    }
    // A durably-failed turn (`#756`) ended without a `batch` — the wire's own
    // doc comment says this field exists so "external surfaces (Slack, the
    // cockpit) can react", but until this event existed no edge ever read it.
    if let Some(failure) = end.failure.into_option() {
        events.push(TurnEvent::TurnFailed {
            kind: turn_failure_kind_from_wire(failure.kind.to_i32()),
            message: failure.message,
        });
    }
    events.push(TurnEvent::Done);
    events
}

/// Map the wire `TurnFailureKind` onto the local, edge-facing
/// [`TurnFailureKind`]. An unrecognized or unspecified wire value maps to
/// [`TurnFailureKind::Other`] — a definite failure with an unclear reason is
/// still a definite failure, never silently dropped.
const fn turn_failure_kind_from_wire(kind: i32) -> TurnFailureKind {
    if kind == WireTurnFailureKind::TURN_FAILURE_KIND_RATE_LIMIT as i32 {
        TurnFailureKind::RateLimit
    } else if kind == WireTurnFailureKind::TURN_FAILURE_KIND_TIMEOUT as i32 {
        TurnFailureKind::Timeout
    } else if kind == WireTurnFailureKind::TURN_FAILURE_KIND_UNAVAILABLE as i32 {
        TurnFailureKind::Unavailable
    } else if kind == WireTurnFailureKind::TURN_FAILURE_KIND_AUTH as i32 {
        TurnFailureKind::Auth
    } else if kind == WireTurnFailureKind::TURN_FAILURE_KIND_BAD_REQUEST as i32 {
        TurnFailureKind::BadRequest
    } else {
        TurnFailureKind::Other
    }
}

/// Project a wire [`ContextCompacted`] into the corresponding
/// [`TurnEvent::ContextCompacted`]. Pure (no I/O); an unknown/unspecified wire
/// reason maps to [`CompactionReason::Truncated`] (the quieter, no-preview
/// rendering) so a future wire reason never panics a live surface.
fn event_from_compacted(c: ContextCompacted) -> TurnEvent {
    let reason = if c.reason.to_i32() == WireCompactionReason::COMPACTION_REASON_SUMMARIZED as i32 {
        CompactionReason::Summarized
    } else {
        CompactionReason::Truncated
    };
    TurnEvent::ContextCompacted {
        reason,
        summarized_messages: c.summarized_messages,
        summary_preview: c.summary_preview,
    }
}

/// Map one output [`Message`] to an optional [`TurnEvent`] for the streaming
/// path.
///
/// Pure (no I/O) so the mapping can be unit-tested without a live stream:
///
/// - A tool-call content block, or any tool-role message, becomes a
///   [`TurnEvent::ToolStarted`] named for the called function (falling back to
///   the call id when the function name is absent).
/// - A non-empty text block on a model/assistant-role message becomes a
///   [`TurnEvent::TextDelta`].
/// - Tool-role text (a tool-result echo) and empty/non-textual blocks produce
///   no event.
/// - An `internal_only` message (`#743`: a paused turn's withheld model text,
///   or an approver/policy-injected note) produces no event — the proto
///   contract is that such a message is never emitted to a client, and the
///   streaming path is exactly that emission seam.
fn message_to_event(msg: Message) -> Option<TurnEvent> {
    if msg.internal_only {
        return None;
    }
    let content_block = msg.content.into_option()?;
    match content_block.r#type? {
        content::Type::ToolCall(tc) => {
            let name = match tc.r#type.as_ref() {
                Some(tool_call_content::Type::FunctionCall(fc)) if !fc.name.is_empty() => {
                    fc.name.clone()
                }
                _ => tc.id.clone(),
            };
            Some(TurnEvent::ToolStarted { name })
        }
        content::Type::Text(t) => {
            if is_assistant_role(&msg.role) && !t.text.is_empty() {
                Some(TurnEvent::TextDelta(t.text))
            } else {
                // Tool-role text is an intermediate result echo; empty text and
                // non-assistant roles carry nothing the user should see.
                None
            }
        }
        // Thoughts, tool results, and media variants have no streaming event in
        // this version.
        _ => None,
    }
}

/// Whether a message role denotes the assistant's own answer text.
///
/// The control plane uses `model` (provider-native) and `assistant`
/// interchangeably for the agent's replies; both count.
fn is_assistant_role(role: &str) -> bool {
    role == "model" || role == "assistant"
}

/// Render one [`content::Type`] variant as user-visible text.
///
/// Returns `None` for variants that have no useful textual representation
/// (image/audio/document/video/confirmation) so the `join("\n")` in
/// [`AgentDialer::run_turn`] doesn't emit stray blank lines.
///
/// Tool calls are rendered (rather than skipped) so a turn that ends on a
/// `tool_call` with no follow-up text — e.g. a HITL pause or approval-only
/// confirmation flow — gives the user something to see instead of an empty
/// body.
fn render_content(ty: Option<content::Type>) -> Option<String> {
    match ty? {
        content::Type::Text(t) => {
            if t.text.is_empty() {
                None
            } else {
                Some(t.text)
            }
        }
        content::Type::ToolCall(tc) => {
            let name = match tc.r#type.as_ref() {
                Some(tool_call_content::Type::FunctionCall(fc)) => fc.name.as_str(),
                None => "",
            };
            if name.is_empty() {
                Some(format!("[tool_call:{}]", tc.id))
            } else {
                Some(format!("[tool_call:{name} {}]", tc.id))
            }
        }
        content::Type::ToolResult(tr) => Some(format!("[tool_result:{}]", tr.call_id)),
        // Everything else renders to no reply text. Notably reasoning
        // (`Thought`): this helper feeds the buffered reply (and its no-text
        // scaffolding fallback), and surfacing reasoning would return raw
        // chain-of-thought as the answer on a tool-only / approval-pause turn.
        // Reasoning reaches the user via a separate path (the TUI builds a
        // collapsed thought line from the proto transcript), never here. Image /
        // audio / document / video / confirmation likewise have no v1 rendering.
        _ => None,
    }
}

/// Classify one output [`Message`] for [`AgentDialer::run_turn_with`]'s
/// buffered aggregation, pushing into `text_parts` (the assistant's real
/// answer) or `scaffolding` (the tool-call/tool-result fallback rendering) —
/// pulled out of the loop body so the classification is unit-testable without
/// a live stream.
///
/// `#743`: an `internal_only` message — a paused turn's withheld model text,
/// or an approver/policy-injected note — is skipped entirely, mirroring
/// [`message_to_event`]'s identical rule on the streaming path so the two
/// APIs cannot drift on what a client is shown.
fn aggregate_output_message(
    msg: Message,
    text_parts: &mut Vec<String>,
    scaffolding: &mut Vec<String>,
) {
    if msg.internal_only {
        return;
    }
    // The turn stream carries every message the turn produced — including the
    // tool-execution result, which the control plane emits as a `tool`-role
    // Text block (the raw tool output, e.g. `{"now":"…"}`). Only the
    // `model`/`assistant` text is the user-facing answer; tool-role text is
    // intermediate data, not the reply.
    let is_assistant = matches!(msg.role.as_str(), "model" | "assistant");
    let Some(content_block) = msg.content.into_option() else {
        return;
    };
    match content_block.r#type {
        Some(content::Type::Text(t)) if is_assistant && !t.text.is_empty() => {
            text_parts.push(t.text);
        }
        // Non-assistant text (tool result echo, user) is not the reply — drop
        // it entirely (not even fallback).
        Some(content::Type::Text(_)) => {}
        // Tool calls/results render as scaffolding fallback; reasoning is
        // excluded by `render_content` (returns None) so raw chain-of-thought
        // never becomes the reply on a tool-only / approval-pause turn.
        other => {
            if let Some(rendered) = render_content(other) {
                scaffolding.push(rendered);
            }
        }
    }
}

/// The buffered result of one turn: the aggregated reply text plus any
/// [`PendingApprovalPrompt`]s the turn paused on.
///
/// Returned by [`AgentDialer::run_turn_with_approvals`] — the buffered
/// sibling of the streaming path's `TurnEvent` sequence, folded into one
/// value since a buffered caller can't react mid-stream anyway.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct BufferedTurn {
    /// The turn's aggregated answer text (identical to what
    /// [`AgentDialer::run_turn_with`] returns).
    pub reply: String,
    /// Gated tool calls the turn paused on, one per entry — empty unless the
    /// turn paused. Submit a decision via [`ApprovalDialer::respond`] for
    /// each, then re-drive with an empty `user_text` to resume the turn.
    pub pending_approvals: Vec<PendingApprovalPrompt>,
}

/// One gated tool call a buffered turn paused on, surfaced from the terminal
/// `AgentEnd.pending_approvals` — the buffered-API mirror of
/// [`TurnEvent::ApprovalPending`]'s fields.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingApprovalPrompt {
    /// Tool-call id == the approval `request_id` to answer.
    pub request_id: String,
    /// The tool/function name awaiting approval. Raw machine identifier; the
    /// field of record for trust/audit.
    pub tool_name: String,
    /// Human display label (MCP-style `title`) for the tool, for rendering in
    /// the approval prompt. May be empty; the surface then derives one from
    /// `tool_name`.
    pub title: String,
    /// Arguments JSON for the call.
    pub args_json: String,
    /// Why this call is gated, when the pause is an OVERRIDE of a call that
    /// would not otherwise need approval. Empty for an ordinary gated call;
    /// non-empty only for the lethal-trifecta / Rule-of-Two containment
    /// override.
    pub reason: String,
    /// The short-lived signed capability (`#787`) that must be replayed
    /// unmodified on the eventual [`ApprovalDialer::respond`] call — required,
    /// the control plane rejects a `Respond` whose token is missing, expired,
    /// or bound to a different request or conversation.
    pub resolve_token: String,
}

/// Every field named explicitly, shared by both the buffered
/// ([`AgentDialer::run_turn_with_approvals`]) and streaming
/// ([`TurnEvent::ApprovalPending`]) paths so the two can't drift on what a
/// pending approval carries — a field added to the wire type without
/// updating this impl fails to compile instead of one path silently not
/// carrying it.
impl From<WireAgentPendingApproval> for PendingApprovalPrompt {
    fn from(pa: WireAgentPendingApproval) -> Self {
        Self {
            request_id: pa.request_id,
            tool_name: pa.tool_name,
            title: pa.title,
            args_json: pa.args_json,
            reason: pa.reason,
            resolve_token: pa.resolve_token,
        }
    }
}

/// [`TurnEvent::ApprovalPending`] carries the exact same fields as
/// [`PendingApprovalPrompt`] — reuse that conversion rather than a second
/// hand-written field list that could drift from it.
impl From<PendingApprovalPrompt> for TurnEvent {
    fn from(p: PendingApprovalPrompt) -> Self {
        Self::ApprovalPending {
            request_id: p.request_id,
            tool_name: p.tool_name,
            title: p.title,
            args_json: p.args_json,
            reason: p.reason,
            resolve_token: p.resolve_token,
        }
    }
}

/// Whether this turn's `AgentEnd` carried a wallet-link prompt (`#519`), and
/// if so, whether a URL was known. A dedicated enum instead of
/// `Option<Option<String>>` (`clippy::option_option`) for the same 3-way
/// distinction: not this turn / this turn with no known URL / this turn with
/// a known URL.
enum WalletLinkPrompt {
    /// This turn carried no wallet-link signal.
    None,
    /// This turn needed a linked wallet; `Some(url)` when the deployment or
    /// per-caller link URL was known, `None` when it wasn't (an admin
    /// pointer is rendered instead).
    Present(Option<String>),
}

/// Decide [`AgentDialer::run_turn_with`]'s final reply string from what the
/// buffered aggregation collected. Pulled out of the loop body so the
/// decision is unit-testable without a live stream, mirroring
/// [`aggregate_output_message`]'s identical rationale.
///
/// A wallet-link-needed turn (`#519` follow-up) REPLACES `text_parts`
/// outright with the deterministic shared-copy prompt — not an append. A
/// third review round found this path shares the same live-delta hazard as
/// Slack/Telegram (`crates/slack/src/handler.rs::interrupt_holdback_text`,
/// `crates/telegram/src/handler.rs`'s reply-override block): `run_turn_with`
/// and the streaming API dial the identical `AgentService.connect` RPC
/// (`build_request`), and the control plane forwards the harness's live
/// `TextDelta`s to EVERY client, buffered or not
/// (`crates/control-plane/src/grpc/mod.rs::should_emit_final_batch` skips
/// re-emitting the `internal_only`-filtered terminal batch whenever any delta
/// was forwarded — the normal case for a streaming provider). So `text_parts`
/// here can just as easily hold the model's own raw, unfiltered "you'll need
/// to link a wallet…" narration as `aggregate_output_message` never sees an
/// `internal_only` flag set on those live deltas (only the terminal batch
/// carries it, and that batch is what gets suppressed). Appending the
/// deterministic prompt on top of that would print both — the exact
/// duplicate-CTA bug this PR exists to fix, just inside one buffered message
/// instead of two Slack bubbles. Buffered edges (discord/email/
/// trigger/cli) only ever post this single final string, so a full replace
/// here is sufficient — there's no earlier partial render to leave stranded.
///
/// `persona_credential_prompt` (PRD #767) gets the identical replace
/// treatment for the same reason — a buffered edge has no card/button
/// surface at all, so it always sees the deterministic narrated-link text,
/// unlike Slack/Telegram which render a labeled button instead. Checked
/// after `wallet_link_prompt`: the two are mutually exclusive in practice
/// (distinct tools), and wallet-link's existing precedence is left
/// undisturbed.
fn finalize_buffered_reply(
    text_parts: &[String],
    scaffolding: &[String],
    wallet_link_prompt: WalletLinkPrompt,
    persona_credential_prompt: Option<&str>,
) -> String {
    if let WalletLinkPrompt::Present(link_url) = wallet_link_prompt {
        return polyc_proto::wallet_link_prompt(link_url.as_deref());
    }
    if let Some(url) = persona_credential_prompt {
        return polyc_proto::persona_credential_prompt(Some(url));
    }
    if text_parts.is_empty() {
        scaffolding.join("\n")
    } else {
        text_parts.join("\n")
    }
}

// ---------------------------------------------------------------------------
// Operator mailbox — the system-initiated, operator-authorized approval path.
//
// The control plane holds no chat tokens; the edges do (docs/design/
// operator-mailbox.md). Delivery therefore splits: the control plane
// ORIGINATES + PERSISTS the ask and exposes a pending-notification projection
// (`NotificationService`); each edge DRAINS the notifications for ITS provider,
// DMs the operator with Approve/Deny controls, and `Ack`s. The decision comes
// home through `OperatorMailboxService.Decide`, where authorization lives
// (server-side, off the edge's already-verified inbound identity).
//
// Both services share the same internal Connect port as the other control-plane
// services, so they are dialed from the same `agent_addr` an edge already holds.
// ---------------------------------------------------------------------------

/// A control-plane action an operator is asked to authorize.
///
/// Lifted to an edge-renderable Rust enum so surfaces match on it without
/// touching the wire crate. Action-agnostic; the upgrade case is the first
/// variant.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OpsAction {
    /// Roll the cluster to a specific release.
    UpgradeTo {
        /// The target release version string, as rendered to the operator.
        version: String,
    },
    /// Nudge an enrolled principal that a routine firing denied fail-closed for
    /// lack of a live grant (`#623`) — a plain, no-decision DM, not an
    /// Approve/Deny ask (see [`OpsAction::is_decision`]).
    EnrollmentNudge {
        /// The routine whose firing denied.
        routine: String,
        /// The enrollment management page the nudge links to, or empty
        /// (`#1264`) when the control plane composed this nudge under a
        /// loopback `POLYCHROME_ENROLLMENT_URL` — a link no reader of this
        /// notice could ever open. [`OpsAction::summary`] renders the
        /// link-omitting fallback in that case.
        ceremony_url: String,
    },
    /// The closed-loop follow-up after an approved `UpgradeTo`: the executor
    /// launched the roll, then the control plane re-observed cluster state
    /// within a bounded window. A plain, no-decision DM (like
    /// `EnrollmentNudge`) reporting an outcome that already happened.
    UpgradeOutcome {
        /// The release version the roll targeted.
        version: String,
        /// What the closed-loop observation confirmed.
        outcome: UpgradeOutcomeKind,
    },
    /// A rendered routine message to post to its pinned destination (`#1122`).
    /// Carries no Approve/Deny decision — the matching edge posts `body` to the
    /// `destination` channel and acks. Delivery is deduplicated by the same
    /// per-`(action_id, target)` marker every notice uses, so a redelivered
    /// notice posts exactly once.
    ContentDelivery {
        /// The synthesized template's name — for labelling/tracing the post.
        template: String,
        /// The pinned, operator-owned destination (e.g. `{"channel": "C0…"}`).
        /// The matching edge posts to the coordinate it recognizes.
        destination: std::collections::BTreeMap<String, String>,
        /// The rendered message body the edge posts verbatim.
        body: String,
    },
    /// An action whose variant this client does not recognise (a newer wire
    /// shape). Rendered generically so an edge never silently drops a real ask.
    Unknown,
}

/// What the closed-loop rollout observation confirmed after an approved
/// `UpgradeTo`, in edge-renderable terms — the buffered analog of the wire
/// `UpgradeOutcome.Kind`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UpgradeOutcomeKind {
    /// Every changed Deployment's rollout confirmed healthy at the target
    /// digests.
    Success,
    /// The observation window elapsed with at least one changed Deployment
    /// confirmed NOT healthy at the target digests.
    Failed,
    /// The observation window elapsed without a confirmed outcome either way
    /// — distinct from `Failed` so the copy never claims to know the roll
    /// broke when it might have simply succeeded unobserved.
    Unknown,
}

/// One undelivered `(item, target)` pair an edge must DM, in edge-friendly
/// terms.
///
/// Mirrors the wire [`PollPendingReply`](polyc_proto::proto::polychrome::ops::v1::PollPendingReply)
/// rows so an edge builds its prompt without importing `polyc-proto`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingNotice {
    /// Opaque idempotency id of the mailbox item — the only token an edge ever
    /// places in unsigned `callback_data`; state is looked up server-side.
    pub action_id: String,
    /// The DM coordinate for THIS provider: a Slack `U…` user id, or a Telegram
    /// `chat_id` as a decimal string.
    pub target: String,
    /// The action to render in the Approve/Deny prompt.
    pub action: OpsAction,
    /// Unix seconds at which the item expires (`0` when unset). An edge may
    /// surface it; a late decision is refused server-side regardless.
    pub expires_unix: u64,
    /// Lowercase-hex BLAKE3 of the canonical payload the operator is approving
    /// (WYSIWYS). The edge echoes this back in [`OperatorMailboxDialer::decide`].
    pub payload_hash: String,
    /// Whether this pair has already been delivered. A delivered pair is still
    /// surfaced so an edge can rehydrate its `action_id -> payload_hash` cache
    /// after a restart; the edge DMs only `delivered == false` pairs.
    pub delivered: bool,
}

/// Reusable handle for the control plane's `NotificationService` — the
/// pending-notification projection an edge drains to deliver operator DMs.
///
/// Shares the `AgentService` endpoint (one internal Connect port), so it is
/// built from the same address an edge already holds.
#[derive(Clone)]
pub struct NotificationDialer {
    client: Arc<NotificationServiceClient<HttpClient>>,
}

impl NotificationDialer {
    /// Build a dialer pointed at `addr` (expects `http://host:port`).
    ///
    /// # Errors
    /// Returns [`DialError::InvalidAddress`] if `addr` isn't a valid URI, or
    /// [`DialError::Tls`] if an `https` endpoint's TLS setup fails.
    pub fn new(addr: &str) -> Result<Self, DialError> {
        let uri = addr
            .parse::<http::Uri>()
            .map_err(|source| DialError::InvalidAddress {
                addr: addr.to_owned(),
                source,
            })?;
        let http = http_client_for(&uri)?;
        let client = NotificationServiceClient::new(
            http,
            ClientConfig::new(uri).with_default_timeout(CONTROL_DIAL_TIMEOUT),
        );
        Ok(Self {
            client: Arc::new(client),
        })
    }

    /// Drain undelivered operator notifications for `provider` (`"slack"` |
    /// `"telegram"`). Read-only and idempotent — the durable mailbox is
    /// unchanged until [`Self::ack`].
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error.
    pub async fn poll_pending(&self, provider: &str) -> Result<Vec<PendingNotice>, DialError> {
        let request = PollPendingRequest {
            provider: provider.to_owned(),
            ..Default::default()
        };
        let reply = self
            .client
            .poll_pending_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(reply.pending.into_iter().map(pending_notice).collect())
    }

    /// Mark an `(action_id, target)` delivered after the DM is sent. Persists
    /// an `ops_action_delivered` marker server-side so the projection survives
    /// restart and never double-delivers. Idempotent: a redundant ack is
    /// harmless.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error.
    pub async fn ack(
        &self,
        provider: &str,
        action_id: &str,
        target: &str,
    ) -> Result<bool, DialError> {
        let request = AckRequest {
            provider: provider.to_owned(),
            action_id: action_id.to_owned(),
            target: target.to_owned(),
            ..Default::default()
        };
        let reply = self
            .client
            .ack_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(reply.persisted)
    }

    /// Server-streaming replacement for [`Self::poll_pending`] (#803): opens a
    /// long-lived `Subscribe` stream that pushes undelivered notifications for
    /// `provider` as they're durably recorded, instead of a fixed polling
    /// interval. The initial connect ALSO catches a freshly (re)started edge up
    /// on whatever is already undelivered — the same coverage a first
    /// `poll_pending` call would give, just pushed rather than pulled.
    ///
    /// # Errors
    /// The outer `Result` carries [`DialError::Connect`] if opening the stream
    /// fails. Each item is a `Result` so a later transport/decode error
    /// surfaces inline without tearing down the whole stream.
    pub async fn subscribe(
        &self,
        provider: &str,
    ) -> Result<impl Stream<Item = Result<PendingNotice, DialError>>, DialError> {
        let request = SubscribeRequest {
            provider: provider.to_owned(),
            ..Default::default()
        };
        let mut stream = self
            .client
            .subscribe_with_options(request, traced_options())
            .await?;
        Ok(async_stream::try_stream! {
            while let Some(view) = stream.message().await? {
                yield pending_notice(view.to_owned_message());
            }
        })
    }
}

/// What [`deliver_content_notice`] did.
///
/// Carried back so a caller with its own metrics conventions (each edge's own
/// `metrics` module — never a dependency of this crate) can still record one.
/// The post/ack orchestration itself, and the tracing that narrates it, live
/// once, here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContentDeliveryOutcome {
    /// Posted and acked.
    Delivered,
    /// The surface-native post failed; the item stays undelivered for a later
    /// retry — safe, because the mailbox's own per-`(action_id, target)`
    /// marker dedups whatever that retry redelivers.
    PostFailed,
    /// The post succeeded but the ack call failed: the message reached its
    /// destination, but the server-side delivered marker didn't land. The
    /// next redrain re-delivers (and re-acks) — at-least-once, deduped
    /// server-side, so this is never a double post.
    AckFailed,
}

/// The shared "post → ack → log" shape every content-delivery notifier used.
///
/// Every edge's `#1122` notifier (Slack, Telegram, Discord) re-implemented
/// this identically (`#1265`, F4), differing only in `post`, the surface-
/// native send primitive; the orchestration around it — ack ONLY after a
/// successful post, so a failed post is retried rather than falsely marked
/// delivered, and the tracing that narrates the outcome — was the same three
/// times over. It now lives once.
///
/// `post` is the edge's surface-native send call — Slack's `post_blocks`,
/// Telegram's `send_message`, Discord's `send_message` — adapted by the
/// caller to `Result<(), E>` (map away the surface's own success payload, if
/// any, with `.map(|_| ())`). Redelivery is idempotent purely by virtue of the
/// mailbox's own per-`(action_id, target)` `Delivered` marker: this function
/// posts and acks unconditionally whenever called, exactly like each edge's
/// original `deliver_content` did — the caller is what skips an
/// already-`delivered` notice (mirroring `deliver_one`'s own
/// `if notice.delivered { return; }` guard) before ever reaching this.
pub async fn deliver_content_notice<F, Fut, E>(
    notifications: &NotificationDialer,
    provider: &str,
    notice: &PendingNotice,
    post: F,
) -> ContentDeliveryOutcome
where
    F: FnOnce() -> Fut,
    Fut: std::future::Future<Output = Result<(), E>>,
    E: std::fmt::Display,
{
    if let Err(err) = post().await {
        tracing::warn!(
            error = %err,
            %provider,
            target = %notice.target,
            "ops notifier: content post failed"
        );
        return ContentDeliveryOutcome::PostFailed;
    }
    match notifications
        .ack(provider, &notice.action_id, &notice.target)
        .await
    {
        Ok(_) => {
            tracing::info!(
                action_id = %notice.action_id,
                %provider,
                target = %notice.target,
                "routine content delivered"
            );
            ContentDeliveryOutcome::Delivered
        }
        Err(err) => {
            tracing::warn!(
                error = %err,
                action_id = %notice.action_id,
                %provider,
                "ops notifier: content ack failed after post"
            );
            ContentDeliveryOutcome::AckFailed
        }
    }
}

/// Map a wire [`PendingNotification`](polyc_proto::proto::polychrome::ops::v1::PendingNotification)
/// to the edge-friendly [`PendingNotice`], lifting the action oneof to
/// [`OpsAction`].
fn pending_notice(
    p: polyc_proto::proto::polychrome::ops::v1::PendingNotification,
) -> PendingNotice {
    let action = p.action.into_option().and_then(|view| view.action).map_or(
        OpsAction::Unknown,
        |a| match a {
            ops_action_view::Action::UpgradeTo(u) => OpsAction::UpgradeTo { version: u.version },
            ops_action_view::Action::EnrollmentNudge(n) => OpsAction::EnrollmentNudge {
                routine: n.routine,
                ceremony_url: n.ceremony_url,
            },
            ops_action_view::Action::UpgradeOutcome(u) => OpsAction::UpgradeOutcome {
                version: u.version,
                outcome: match u.kind.as_known() {
                    Some(upgrade_outcome::Kind::SUCCESS) => UpgradeOutcomeKind::Success,
                    Some(upgrade_outcome::Kind::FAILED) => UpgradeOutcomeKind::Failed,
                    Some(
                        upgrade_outcome::Kind::UNKNOWN | upgrade_outcome::Kind::KIND_UNSPECIFIED,
                    )
                    | None => UpgradeOutcomeKind::Unknown,
                },
            },
            ops_action_view::Action::ContentDelivery(c) => OpsAction::ContentDelivery {
                template: c.template,
                destination: c.destination.into_iter().collect(),
                body: c.body,
            },
        },
    );
    PendingNotice {
        action_id: p.action_id,
        target: p.target,
        action,
        expires_unix: p.expires_unix,
        payload_hash: p.payload_hash,
        delivered: p.delivered,
    }
}

/// One active enrollment of a routine, as the trigger edge reads it for
/// fire-time fan-out (#622) — the edge-facing analog of the wire
/// `routine.v1.LiveEnrollment`.
///
/// Every field is present because the control plane returns only ACTIVE
/// enrollments: `conversation_id` is the deterministic per-`(routine, principal)`
/// partition each firing lands in, and `notify` is the identity the firing
/// attributes the turn's caller to.
#[derive(Debug, Clone, PartialEq)]
pub struct LiveEnrollment {
    /// The enrolled principal (persona id) the turn runs as.
    pub persona_id: String,
    /// The chat identity the firing attributes the turn's caller to (and #623
    /// nudges when paused).
    pub notify: ExternalIdentity,
    /// The deterministic per-`(routine, principal)` conversation id the firing
    /// dials — stable across firings, distinct per principal.
    pub conversation_id: String,
}

impl From<polyc_proto::proto::polychrome::routine::v1::LiveEnrollment> for LiveEnrollment {
    fn from(e: polyc_proto::proto::polychrome::routine::v1::LiveEnrollment) -> Self {
        Self {
            persona_id: e.persona_id,
            notify: e.notify_identity.into_option().unwrap_or_default(),
            conversation_id: e.conversation_id,
        }
    }
}

/// The trigger edge's fire-time view of one routine (#622): whether the id is
/// an enrolled routine at all, and its active enrollments.
///
/// The edge fans out one turn per [`active`](Self::active) enrollment only when
/// [`known`](Self::known) is true. A `known == false` id was never a routine —
/// a plain cron job — so the edge falls back to its single-conversation firing
/// and existing cron flows are untouched.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct RoutineEnrollments {
    /// Whether at least one principal has ever enrolled in this routine (active,
    /// paused, or disenrolled). False for an id that was never a routine.
    pub known: bool,
    /// The active enrollments — the fire-time set. Empty (with `known == true`)
    /// for an enrolled routine whose enrollments are all paused: fire nothing.
    pub active: Vec<LiveEnrollment>,
}

/// Reusable handle for the control plane's `RoutineService` — the
/// live-enrollments-per-routine projection the trigger edge enumerates at fire
/// time (#622).
///
/// Shares the `AgentService` endpoint (one internal Connect port), so it is
/// built from the same address an edge already holds.
#[derive(Clone)]
pub struct LiveEnrollmentsDialer {
    client: Arc<RoutineServiceClient<HttpClient>>,
}

impl LiveEnrollmentsDialer {
    /// Build a dialer pointed at `addr` (expects `http://host:port`).
    ///
    /// # Errors
    /// Returns [`DialError::InvalidAddress`] if `addr` isn't a valid URI, or
    /// [`DialError::Tls`] if an `https` endpoint's TLS setup fails.
    pub fn new(addr: &str) -> Result<Self, DialError> {
        let uri = addr
            .parse::<http::Uri>()
            .map_err(|source| DialError::InvalidAddress {
                addr: addr.to_owned(),
                source,
            })?;
        let http = http_client_for(&uri)?;
        let client = RoutineServiceClient::new(
            http,
            ClientConfig::new(uri).with_default_timeout(CONTROL_DIAL_TIMEOUT),
        );
        Ok(Self {
            client: Arc::new(client),
        })
    }

    /// Resolve `routine`'s fire-time view: whether it is an enrolled routine and
    /// its active enrollments.
    ///
    /// `bearer_token` is the caller's raw Kubernetes `ServiceAccount` token (no
    /// `Bearer ` prefix) for a `Cron` firing — forwarded unverified; the
    /// control plane verifies it via `TokenReview` before returning anything
    /// (`docs/adr/0005-serviceaccount-tokenreview-trigger-auth.md`). Empty for
    /// any caller that isn't a `Cron` firing.
    ///
    /// The edge fans out only when [`RoutineEnrollments::known`] is true; a
    /// `known == false` id was never a routine, so the edge falls back to its
    /// single-conversation firing and existing cron flows are untouched.
    ///
    /// With `originate_nudges` set, the control plane also runs the
    /// paused-principal nudge pass as a side effect of this call (one nudge
    /// per armed paused enrollment, deduped by marker) — the fire-time
    /// contract. Pass `false` for a read-only listing.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error — in
    /// particular `Unauthenticated`/`PermissionDenied` when `bearer_token`
    /// fails verification or names the wrong routine's identity; the caller
    /// must check [`DialError::code`] rather than treat every error as
    /// "unknown routine, fall back."
    pub async fn list(
        &self,
        routine: &str,
        bearer_token: &str,
        originate_nudges: bool,
    ) -> Result<RoutineEnrollments, DialError> {
        let mut active = Vec::new();
        let mut page_token = String::new();
        let known = loop {
            // The nudge pass is a side effect of the FIRST page only — it's
            // idempotent (deduped by the durable `nudge_sent` marker) so a
            // repeat wouldn't corrupt anything, but there's no reason to pay
            // for the extra replay check on every subsequent page of the same
            // fire-time listing.
            let request = ListLiveEnrollmentsRequest {
                routine: routine.to_owned(),
                originate_nudges: originate_nudges && page_token.is_empty(),
                page_token: page_token.clone(),
                bearer_token: bearer_token.to_owned(),
                ..Default::default()
            };
            let reply = self
                .client
                .list_live_enrollments_with_options(request, traced_options())
                .await?
                .into_owned();
            active.extend(reply.enrollments.into_iter().map(LiveEnrollment::from));
            if reply.next_page_token.is_empty() {
                break reply.known;
            }
            page_token = reply.next_page_token;
        };
        Ok(RoutineEnrollments { known, active })
    }

    /// Start a routine-join enrollment ceremony for `notify_identity` and return
    /// the browser URL the person opens to finish enrolling.
    ///
    /// The control plane resolves (or provisions) the persona, resolves the named
    /// routine, builds the envelope-bounded offer, and mints a one-time ceremony
    /// session. Fails when the routine is unknown or invalid, or when the pair is
    /// already actively enrolled.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error, which
    /// carries the control plane's Connect error (unknown routine, already
    /// enrolled, or an unconfigured mint trigger).
    pub async fn start_enrollment(
        &self,
        routine: &str,
        notify_identity: ExternalIdentity,
    ) -> Result<StartedEnrollment, DialError> {
        let request = StartEnrollmentRequest {
            routine: routine.to_owned(),
            notify_identity: buffa::MessageField::some(notify_identity),
            ..Default::default()
        };
        let reply = self
            .client
            .start_enrollment_with_options(request, traced_options())
            .await?
            .into_owned();
        Ok(StartedEnrollment {
            ceremony_url: reply.ceremony_url,
            enrollment_id: reply.enrollment_id,
            persona_id: reply.persona_id,
        })
    }
}

/// The result of [`LiveEnrollmentsDialer::start_enrollment`]: the ceremony URL
/// the person opens, plus the ids the control plane minted.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StartedEnrollment {
    /// The ceremony URL to open in a browser to finish enrolling — an
    /// `apps/wallet` route (`{enrollment_base_url}?token={token}`, #899).
    pub ceremony_url: String,
    /// The enrollment id the minted session is keyed by.
    pub enrollment_id: String,
    /// The persona the routine will run as, resolved from the notify identity.
    pub persona_id: String,
}

/// The control plane's verdict on an operator decision, in edge-renderable
/// terms — the buffered analog of the wire `DecideReply.Outcome`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DecideOutcome {
    /// Approved, authorized, signed + recorded, handed to the executor.
    Applied,
    /// The operator denied it; the denial was recorded.
    Denied,
    /// Refused — not an operator / unknown action / already decided / expired /
    /// payload drift. `detail` carries the human-readable reason.
    Rejected,
    /// An unspecified/unknown outcome — the edge surfaces a generic failure
    /// rather than claiming success.
    Unknown,
}

/// An operator decision's result: the [`DecideOutcome`] plus the control
/// plane's human-readable `detail` (the reject reason when rejected).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecideResult {
    /// The verdict.
    pub outcome: DecideOutcome,
    /// Human-readable detail to surface to the operator.
    pub detail: String,
}

/// Heading shown above an approval-mailbox prompt.
///
/// Shared across edges so the two surfaces never word the same ask differently,
/// and to keep internal jargon out of user-facing copy — an edge only wraps this
/// in its own markup.
pub const OPS_PROMPT_HEADING: &str = "Approval needed";

impl OpsAction {
    /// Plain description of the action for an approval prompt — the single
    /// wording both edges render, so an added action variant is described once
    /// and never diverges between surfaces.
    ///
    /// An `UpgradeTo` ask is worded through the shared
    /// [`update_copy`](polyc_runtime::update_copy::update_copy) helper — the same
    /// one the CLI `status` line and the dashboard banner use — so a person reads
    /// the identical "update ready" copy wherever it surfaces. Rolling the cluster
    /// to a new release replaces the running image, so the change is
    /// [`Compatibility::Warm`](polyc_runtime::compat::Compatibility::Warm): it
    /// restarts the service, and conversations already underway finish first.
    #[must_use]
    pub fn summary(&self) -> String {
        match self {
            Self::UpgradeTo { version } => {
                let copy = polyc_runtime::update_copy::update_copy(
                    &polyc_runtime::compat::Compatibility::Warm,
                    version,
                );
                format!("{}{}", copy.headline, copy.detail)
            }
            // Purpose (why it stalled) + the exact next step + where to take it,
            // in one sentence — no jargon, no decision to make here (that's
            // `is_decision`), just the link.
            //
            // An empty `ceremony_url` (#1264) means the control plane composed
            // this nudge under a loopback `POLYCHROME_ENROLLMENT_URL` — a link
            // no reader of this notice could ever open, since a nudge is always
            // read on an external surface. Say where to go instead of shipping
            // an address that can never resolve.
            Self::EnrollmentNudge {
                routine,
                ceremony_url,
            } => {
                if ceremony_url.is_empty() {
                    format!(
                        "The {routine} routine could not run because its approval is missing. \
                         Ask whoever runs your deployment where to re-approve it."
                    )
                } else {
                    format!(
                        "The {routine} routine could not run because its approval is \
                         missing. Approve it on the enrollment page and the next \
                         scheduled run will go through: {ceremony_url}"
                    )
                }
            }
            // The closed-loop follow-up: reports what the approved roll
            // actually did, never claiming success it couldn't confirm.
            Self::UpgradeOutcome { version, outcome } => match outcome {
                UpgradeOutcomeKind::Success => {
                    format!("✅ The cluster is now running {version}.")
                }
                UpgradeOutcomeKind::Failed => format!(
                    "⚠️ The upgrade to {version} did not confirm healthy — check `polychrome status`."
                ),
                UpgradeOutcomeKind::Unknown => format!(
                    "❓ Could not confirm whether the upgrade to {version} finished — check `polychrome status`."
                ),
            },
            // The rendered routine message itself is what a person reads — the
            // edge posts this `body` verbatim to the pinned destination, so the
            // notice's own text IS the body (no wrapper, no jargon).
            Self::ContentDelivery { body, .. } => body.clone(),
            // Jargon-free fallback for an action this client doesn't recognize.
            Self::Unknown => "Approve a pending action".to_owned(),
        }
    }

    /// The rendered `(destination, body)` when this action is a routine content
    /// delivery (`#1122`), for the edge to post to the destination channel;
    /// `None` for every other action. Lets a notifier route a delivery to a
    /// channel post rather than the operator-DM path without matching the wire
    /// oneof itself.
    #[must_use]
    pub const fn content_delivery(
        &self,
    ) -> Option<(&std::collections::BTreeMap<String, String>, &str)> {
        match self {
            Self::ContentDelivery {
                destination, body, ..
            } => Some((destination, body.as_str())),
            _ => None,
        }
    }

    /// The exact verb an edge puts on the approve affordance for this action, or
    /// `None` to fall back to a generic "Approve".
    ///
    /// An `UpgradeTo` ask that can be applied in place carries the shared
    /// [`APPLY_NOW`](polyc_runtime::update_copy::APPLY_NOW) verb, routed through
    /// the same helper as [`Self::summary`] so the button never words the update
    /// differently from its detail. A cold or incompatible change would carry no
    /// verb here; a cluster roll is always warm, so the upgrade ask carries the
    /// apply verb.
    #[must_use]
    pub fn approve_verb(&self) -> Option<&'static str> {
        match self {
            Self::UpgradeTo { version } => {
                polyc_runtime::update_copy::update_copy(
                    &polyc_runtime::compat::Compatibility::Warm,
                    version,
                )
                .action
            }
            Self::EnrollmentNudge { .. }
            | Self::UpgradeOutcome { .. }
            | Self::ContentDelivery { .. }
            | Self::Unknown => None,
        }
    }

    /// Whether this action carries an Approve/Deny decision at all.
    ///
    /// An [`OpsAction::EnrollmentNudge`] is a plain, informational DM — nothing
    /// names it in `OperatorMailboxService.Decide` — so an edge renders it as a
    /// link message with no buttons. An [`OpsAction::UpgradeOutcome`] is the
    /// same shape: it reports something that already happened, not an ask.
    /// Every other known action (and `Unknown`, defensively — a future wire
    /// shape this client doesn't recognize yet still gets rendered as a
    /// decidable ask rather than silently dropped) is decidable.
    #[must_use]
    pub const fn is_decision(&self) -> bool {
        !matches!(
            self,
            Self::EnrollmentNudge { .. }
                | Self::UpgradeOutcome { .. }
                | Self::ContentDelivery { .. }
        )
    }
}

impl DecideOutcome {
    /// Metric label for this outcome (`applied` | `denied` | `rejected` |
    /// `unknown`) — shared so the two edges never emit divergent label sets for
    /// the same control-plane verdict.
    #[must_use]
    pub const fn metric_label(&self) -> &'static str {
        match self {
            Self::Applied => "applied",
            Self::Denied => "denied",
            Self::Rejected => "rejected",
            Self::Unknown => "unknown",
        }
    }
}

impl DecideResult {
    /// The decided-state line that REPLACES an approval prompt after a decision
    /// (the double-click guard drops the buttons). Surfaces the control plane's
    /// verdict and, on a rejection, its `detail`. Shared so both edges show the
    /// same wording for the same verdict.
    #[must_use]
    pub fn decided_line(&self, decider: &str) -> String {
        match self.outcome {
            DecideOutcome::Applied => format!("✅ Approved by {decider} — applying."),
            DecideOutcome::Denied => format!("🚫 Denied by {decider}."),
            DecideOutcome::Rejected => {
                let why = if self.detail.is_empty() {
                    "not authorized or no longer valid"
                } else {
                    self.detail.as_str()
                };
                format!("⛔ Rejected — {why}.")
            }
            DecideOutcome::Unknown => {
                "⚠️ Something went wrong recording that decision — try again.".to_owned()
            }
        }
    }
}

/// Reusable handle for the control plane's `OperatorMailboxService` — the
/// operator decision endpoint (authorize → evaluate → sign → record →
/// executor, all server-side).
///
/// Shares the `AgentService` endpoint (one internal Connect port), so it is
/// built from the same address an edge already holds.
#[derive(Clone)]
pub struct OperatorMailboxDialer {
    client: Arc<OperatorMailboxServiceClient<HttpClient>>,
}

impl OperatorMailboxDialer {
    /// Build a dialer pointed at `addr` (expects `http://host:port`).
    ///
    /// # Errors
    /// Returns [`DialError::InvalidAddress`] if `addr` isn't a valid URI, or
    /// [`DialError::Tls`] if an `https` endpoint's TLS setup fails.
    pub fn new(addr: &str) -> Result<Self, DialError> {
        let uri = addr
            .parse::<http::Uri>()
            .map_err(|source| DialError::InvalidAddress {
                addr: addr.to_owned(),
                source,
            })?;
        let http = http_client_for(&uri)?;
        let client = OperatorMailboxServiceClient::new(
            http,
            ClientConfig::new(uri).with_default_timeout(CONTROL_DIAL_TIMEOUT),
        );
        Ok(Self {
            client: Arc::new(client),
        })
    }

    /// Submit an operator decision for `action_id`. Authorization is
    /// SERVER-SIDE: the edge forwards the `(provider, external_user_id)` it
    /// already authenticated (Slack HMAC / Telegram `secret_token`) and the
    /// control plane resolves it to an operator persona, refusing non-operators.
    /// `payload_hash` is the WYSIWYS hash the edge displayed; the control plane
    /// refuses an approval whose hash drifted from the live item.
    ///
    /// Idempotent: a duplicate Approve click on an already-decided item is
    /// [`DecideOutcome::Rejected`], never double-applied.
    ///
    /// # Errors
    /// Returns [`DialError::Connect`] for any transport/encoding error.
    pub async fn decide(
        &self,
        action_id: &str,
        approved: bool,
        provider: &str,
        external_user_id: &str,
        reason: &str,
        payload_hash: &str,
    ) -> Result<DecideResult, DialError> {
        let request = DecideRequest {
            action_id: action_id.to_owned(),
            approved,
            provider: provider.to_owned(),
            external_user_id: external_user_id.to_owned(),
            reason: reason.to_owned(),
            payload_hash: payload_hash.to_owned(),
            ..Default::default()
        };
        let reply = self
            .client
            .decide_with_options(request, traced_options())
            .await?
            .into_owned();
        let outcome = match reply.outcome.as_known() {
            Some(decide_reply::Outcome::APPLIED) => DecideOutcome::Applied,
            Some(decide_reply::Outcome::DENIED) => DecideOutcome::Denied,
            Some(decide_reply::Outcome::REJECTED) => DecideOutcome::Rejected,
            Some(decide_reply::Outcome::OUTCOME_UNSPECIFIED) | None => DecideOutcome::Unknown,
        };
        Ok(DecideResult {
            outcome,
            detail: reply.detail,
        })
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use super::*;
    use polyc_proto::proto::polychrome::agent::v1::{
        Content, FunctionCallContent, TextContent, ThoughtContent, ThoughtSummaryContent,
        ToolCallContent, ToolResultContent, thought_summary_content,
    };

    #[test]
    fn ops_copy_is_shared_and_jargon_free() {
        // The upgrade ask is worded through the shared update-copy helper: it
        // names the version, carries the exact "Apply now" verb (a cluster roll
        // is a warm, in-place restart), and reads identically to the CLI and
        // dashboard surfaces.
        let up = OpsAction::UpgradeTo {
            version: "1.2.3".to_owned(),
        };
        let summary = up.summary();
        assert!(
            summary.contains("1.2.3"),
            "summary names the version: {summary}"
        );
        assert!(
            summary.contains("restarts the service"),
            "warm upgrade summary is honest about the restart: {summary}"
        );
        assert_eq!(
            up.approve_verb(),
            Some(polyc_runtime::update_copy::APPLY_NOW),
            "an in-place upgrade carries the shared Apply now verb"
        );
        assert!(
            !summary.to_lowercase().contains("operator"),
            "no banned jargon in the upgrade ask: {summary}"
        );
        assert_eq!(OpsAction::Unknown.approve_verb(), None);
        let unknown = OpsAction::Unknown.summary();
        assert!(!unknown.to_lowercase().contains("control-plane"));
        assert!(!unknown.is_empty());
        // The shared heading carries no banned jargon.
        assert!(!OPS_PROMPT_HEADING.to_lowercase().contains("operator"));

        // Metric labels are stable and distinct.
        assert_eq!(DecideOutcome::Applied.metric_label(), "applied");
        assert_eq!(DecideOutcome::Denied.metric_label(), "denied");
        assert_eq!(DecideOutcome::Rejected.metric_label(), "rejected");
        assert_eq!(DecideOutcome::Unknown.metric_label(), "unknown");

        // The decided line surfaces each verdict, the decider, and reject detail,
        // and never says "please".
        let applied = DecideResult {
            outcome: DecideOutcome::Applied,
            detail: String::new(),
        }
        .decided_line("Chris");
        assert!(applied.contains("Approved") && applied.contains("Chris"));
        let rejected = DecideResult {
            outcome: DecideOutcome::Rejected,
            detail: "not an operator".to_owned(),
        }
        .decided_line("Chris");
        assert!(rejected.contains("Rejected") && rejected.contains("not an operator"));
        let unknown = DecideResult {
            outcome: DecideOutcome::Unknown,
            detail: String::new(),
        }
        .decided_line("Chris");
        assert!(!unknown.to_lowercase().contains("please"));
    }

    #[test]
    fn enrollment_nudge_copy_is_a_link_not_a_decision() {
        // #623: the nudge is purpose + next step + link, in one sentence, and
        // carries no decision — an edge renders it with no Approve/Deny controls.
        let nudge = OpsAction::EnrollmentNudge {
            routine: "standup".to_owned(),
            ceremony_url: "https://enroll.polychrome.test/v1/enroll/manage/standup/persona-9"
                .to_owned(),
        };
        assert!(!nudge.is_decision(), "a nudge carries no approve/deny");
        assert_eq!(nudge.approve_verb(), None);
        let summary = nudge.summary();
        assert!(summary.contains("standup"), "names the routine: {summary}");
        assert!(
            summary.contains("https://enroll.polychrome.test/v1/enroll/manage/standup/persona-9"),
            "carries the exact ceremony link: {summary}"
        );
        // No banned jargon, no "please"/"sorry"/"unfortunately".
        let lower = summary.to_lowercase();
        for banned in [
            "operator",
            "sub-agent",
            "trifecta",
            "context budget",
            "state-changing action",
            "please",
            "sorry",
            "unfortunately",
        ] {
            assert!(
                !lower.contains(banned),
                "banned word {banned:?} in: {summary}"
            );
        }
        // Upgrade asks stay decidable — this is additive, not a regression.
        assert!(
            OpsAction::UpgradeTo {
                version: "1.2.3".to_owned()
            }
            .is_decision()
        );
        assert!(OpsAction::Unknown.is_decision());
    }

    /// #1264: a nudge composed under a loopback `POLYCHROME_ENROLLMENT_URL`
    /// carries an empty `ceremony_url` — the control plane never ships a link
    /// no reader of the notice could ever open. `summary` must fall back to
    /// copy that names the routine and says where to go instead, with no
    /// stray link and no banned jargon.
    #[test]
    fn enrollment_nudge_omits_the_link_when_composed_under_a_loopback_base() {
        let nudge = OpsAction::EnrollmentNudge {
            routine: "standup".to_owned(),
            ceremony_url: String::new(),
        };
        assert!(!nudge.is_decision(), "still a plain DM, not a decision");
        let summary = nudge.summary();
        assert!(
            summary.contains("standup"),
            "still names the routine: {summary}"
        );
        assert!(
            !summary.contains("http"),
            "no link of any scheme ships when the base was unreachable: {summary}"
        );
        let lower = summary.to_lowercase();
        for banned in [
            "operator",
            "sub-agent",
            "trifecta",
            "context budget",
            "state-changing action",
            "please",
            "sorry",
            "unfortunately",
        ] {
            assert!(
                !lower.contains(banned),
                "banned word {banned:?} in: {summary}"
            );
        }
    }

    // ── #1122: routine content delivery is a channel post, not a decision ─────

    #[test]
    fn content_delivery_maps_off_the_wire_and_is_a_channel_post() {
        use polyc_proto::proto::polychrome::ops::v1::{
            ContentDelivery as WireContentDelivery, OpsActionView, PendingNotification,
            ops_action_view,
        };
        let wire = PendingNotification {
            action_id: "content_delivery:tick-42:standup_summary_v1".to_owned(),
            target: "C0STANDUP".to_owned(),
            action: buffa::MessageField::some(OpsActionView {
                action: Some(ops_action_view::Action::ContentDelivery(Box::new(
                    WireContentDelivery {
                        template: "standup_summary_v1".to_owned(),
                        destination: [("channel".to_owned(), "C0STANDUP".to_owned())]
                            .into_iter()
                            .collect(),
                        body: "shipped the release".to_owned(),
                        ..Default::default()
                    },
                ))),
                ..Default::default()
            }),
            delivered: false,
            ..Default::default()
        };
        let notice = super::pending_notice(wire);
        // It renders as a content delivery, not a decision.
        assert!(
            !notice.action.is_decision(),
            "no approve/deny on a delivery"
        );
        assert_eq!(notice.action.approve_verb(), None);
        // The edge reads the destination + body straight off the accessor.
        let (destination, body) = notice
            .action
            .content_delivery()
            .expect("a content delivery exposes its destination + body");
        assert_eq!(
            destination.get("channel").map(String::as_str),
            Some("C0STANDUP")
        );
        assert_eq!(body, "shipped the release");
        // The rendered body is what a person reads — summary IS the body.
        assert_eq!(notice.action.summary(), "shipped the release");
        // Every other action returns None from the accessor.
        assert!(
            OpsAction::UpgradeTo {
                version: "1.0.0".to_owned()
            }
            .content_delivery()
            .is_none()
        );
    }

    #[test]
    fn approval_choice_flags() {
        assert!(ApprovalChoice::Approve.approved());
        assert!(!ApprovalChoice::Approve.approved_for_session());
        assert!(!ApprovalChoice::Approve.is_abort());
        assert!(ApprovalChoice::ApproveForSession.approved());
        assert!(ApprovalChoice::ApproveForSession.approved_for_session());
        // Deny and Abort both decline; only Abort stops the turn.
        assert!(!ApprovalChoice::Deny.approved());
        assert!(!ApprovalChoice::Deny.is_abort());
        assert!(!ApprovalChoice::Abort.approved());
        assert!(ApprovalChoice::Abort.is_abort());
    }

    /// `#743`: the completed-card line names the tool, the decider, and the
    /// outcome — the runtime's report of what actually happened, distinct
    /// from `approval_decided_text`'s earlier "running…" line.
    #[test]
    fn approval_completed_text_reports_the_runtime_outcome() {
        let done = approval_completed_text("Remove @vitor's admin role", "Chris", true);
        assert!(done.contains("Chris"), "names the decider: {done}");
        assert!(
            done.contains("Remove @vitor's admin role"),
            "names the tool label: {done}"
        );
        assert!(done.contains("done"), "a success reads as done: {done}");

        let failed = approval_completed_text("Remove @vitor's admin role", "Chris", false);
        assert_ne!(
            done, failed,
            "success and failure must not read identically"
        );
        assert!(
            failed.contains("error"),
            "a failed run must say so, not claim success: {failed}"
        );

        for copy in [&done, &failed] {
            let lower = copy.to_lowercase();
            for banned in ["please", "sorry", "unfortunately", "operator"] {
                assert!(
                    !lower.contains(banned),
                    "banned word {banned:?} in {copy:?}"
                );
            }
        }
    }

    #[test]
    fn compacted_summarized_maps_with_preview() {
        let c = ContextCompacted {
            reason: buffa::EnumValue::from(
                WireCompactionReason::COMPACTION_REASON_SUMMARIZED as i32,
            ),
            summarized_messages: 12,
            summary_preview: "earlier work: fixed bug X".to_owned(),
            ..Default::default()
        };
        assert_eq!(
            event_from_compacted(c),
            TurnEvent::ContextCompacted {
                reason: CompactionReason::Summarized,
                summarized_messages: 12,
                summary_preview: "earlier work: fixed bug X".to_owned(),
            }
        );
    }

    #[test]
    fn compacted_truncated_maps_without_preview() {
        let c = ContextCompacted {
            reason: buffa::EnumValue::from(
                WireCompactionReason::COMPACTION_REASON_TRUNCATED as i32,
            ),
            ..Default::default()
        };
        assert_eq!(
            event_from_compacted(c),
            TurnEvent::ContextCompacted {
                reason: CompactionReason::Truncated,
                summarized_messages: 0,
                summary_preview: String::new(),
            }
        );
    }

    #[test]
    fn compacted_unknown_reason_falls_back_to_truncated() {
        // An unspecified/future wire reason must not panic a live surface; it
        // maps to the quieter, no-preview rendering.
        let c = ContextCompacted {
            reason: buffa::EnumValue::from(
                WireCompactionReason::COMPACTION_REASON_UNSPECIFIED as i32,
            ),
            ..Default::default()
        };
        assert!(matches!(
            event_from_compacted(c),
            TurnEvent::ContextCompacted {
                reason: CompactionReason::Truncated,
                ..
            }
        ));
    }

    #[test]
    fn dial_error_retryable_classification() {
        use connectrpc::ErrorCode;
        // Transient transport conditions → retryable (ask for redelivery).
        for code in [
            ErrorCode::Unavailable,
            ErrorCode::DeadlineExceeded,
            ErrorCode::ResourceExhausted,
            ErrorCode::Aborted,
        ] {
            let err = DialError::Connect(connectrpc::ConnectError::new(code, "x"));
            assert_eq!(err.code(), Some(code));
            assert!(err.is_retryable(), "{code:?} should be retryable");
        }
        // Terminal codes → NOT retryable (redelivery would loop forever).
        for code in [
            ErrorCode::InvalidArgument,
            ErrorCode::Unauthenticated,
            ErrorCode::NotFound,
            ErrorCode::PermissionDenied,
            ErrorCode::Internal,
        ] {
            let err = DialError::Connect(connectrpc::ConnectError::new(code, "x"));
            assert_eq!(err.code(), Some(code));
            assert!(!err.is_retryable(), "{code:?} should not be retryable");
        }
        // Local failures carry no Connect code and are never retryable.
        let bad_addr = DialError::InvalidAddress {
            addr: "http://a b".to_owned(),
            source: "http://a b".parse::<http::Uri>().unwrap_err(),
        };
        assert_eq!(bad_addr.code(), None);
        assert!(!bad_addr.is_retryable());
        let tls = DialError::Tls("no provider".to_owned());
        assert_eq!(tls.code(), None);
        assert!(!tls.is_retryable());
    }

    fn text(s: &str) -> Option<content::Type> {
        Some(content::Type::Text(Box::new(TextContent {
            text: s.to_owned(),
            ..Default::default()
        })))
    }

    fn tool_call(id: &str, name: &str) -> Option<content::Type> {
        Some(content::Type::ToolCall(Box::new(ToolCallContent {
            id: id.to_owned(),
            r#type: Some(tool_call_content::Type::FunctionCall(Box::new(
                FunctionCallContent {
                    name: name.to_owned(),
                    ..Default::default()
                },
            ))),
            ..Default::default()
        })))
    }

    fn tool_result(call_id: &str) -> Option<content::Type> {
        Some(content::Type::ToolResult(Box::new(ToolResultContent {
            call_id: call_id.to_owned(),
            ..Default::default()
        })))
    }

    fn thought(summary: &str) -> Option<content::Type> {
        Some(content::Type::Thought(Box::new(ThoughtContent {
            summary: vec![ThoughtSummaryContent {
                r#type: Some(thought_summary_content::Type::Text(Box::new(TextContent {
                    text: summary.to_owned(),
                    ..Default::default()
                }))),
                ..Default::default()
            }],
            ..Default::default()
        })))
    }

    #[test]
    fn renders_text_verbatim() {
        assert_eq!(render_content(text("hi")), Some("hi".to_owned()));
    }

    #[test]
    fn renders_tool_call_with_name_and_id() {
        assert_eq!(
            render_content(tool_call("call_42", "search")),
            Some("[tool_call:search call_42]".to_owned())
        );
    }

    #[test]
    fn renders_tool_call_without_function_name() {
        assert_eq!(
            render_content(Some(content::Type::ToolCall(Box::new(ToolCallContent {
                id: "call_bare".to_owned(),
                r#type: None,
                ..Default::default()
            })))),
            Some("[tool_call:call_bare]".to_owned())
        );
    }

    #[test]
    fn renders_tool_result_by_call_id() {
        assert_eq!(
            render_content(tool_result("call_42")),
            Some("[tool_result:call_42]".to_owned())
        );
    }

    #[test]
    fn reasoning_is_never_the_reply() {
        // Reasoning must NOT render into the buffered reply (raw chain-of-thought
        // as the answer). It is shown via the TUI's separate transcript path.
        assert_eq!(render_content(thought("considering options")), None);
    }

    #[test]
    fn thought_only_turn_yields_empty_reply() {
        // A turn that produced only reasoning (no answer text, no tool calls)
        // must come back empty, not with the chain-of-thought as the reply.
        assert_eq!(aggregate(vec![thought("secret reasoning")]), "");
    }

    #[test]
    fn empty_text_skipped() {
        assert_eq!(render_content(text("")), None);
    }

    #[test]
    fn unknown_variant_skipped() {
        // No content::Type set at all.
        assert_eq!(render_content(None), None);
    }

    // Helper used by aggregation tests: feed the same rendering loop
    // run_turn uses, but driven from a vector of fake content blocks rather
    // than a live connectrpc stream.
    fn aggregate(blocks: Vec<Option<content::Type>>) -> String {
        let mut parts: Vec<String> = Vec::new();
        for b in blocks {
            if let Some(s) = render_content(b) {
                parts.push(s);
            }
        }
        parts.join("\n")
    }

    #[test]
    fn aggregate_pure_text_turn() {
        assert_eq!(
            aggregate(vec![text("hello"), text("world")]),
            "hello\nworld"
        );
    }

    #[test]
    fn aggregate_tool_call_only_turn() {
        // A turn that ends in a tool call with no follow-up text used to
        // come back as "" and was silently dropped by the Slack handler.
        // Rendering a placeholder keeps the user informed.
        assert_eq!(
            aggregate(vec![tool_call("call_1", "lookup")]),
            "[tool_call:lookup call_1]"
        );
    }

    #[test]
    fn aggregate_mixed_text_and_tool_call() {
        assert_eq!(
            aggregate(vec![text("thinking..."), tool_call("call_1", "search")]),
            "thinking...\n[tool_call:search call_1]"
        );
    }

    /// `#743`: the buffered aggregation path must skip `internal_only`
    /// messages entirely — neither the assistant-text nor the scaffolding
    /// leg — mirroring `message_to_event`'s streaming-path rule.
    #[test]
    fn buffered_aggregation_skips_internal_only_messages() {
        let mut withheld = message("model", text("pending your approval"));
        withheld.internal_only = true;
        let mut text_parts = Vec::new();
        let mut scaffolding = Vec::new();
        aggregate_output_message(withheld, &mut text_parts, &mut scaffolding);
        assert!(
            text_parts.is_empty(),
            "withheld text must not become the reply"
        );
        assert!(
            scaffolding.is_empty(),
            "withheld text must not fall back to scaffolding either"
        );
    }

    #[test]
    fn buffered_aggregation_keeps_visible_assistant_text() {
        // Regression: a normal (non-internal_only) assistant message must
        // still aggregate exactly as before.
        let mut text_parts = Vec::new();
        let mut scaffolding = Vec::new();
        aggregate_output_message(
            message("model", text("the answer")),
            &mut text_parts,
            &mut scaffolding,
        );
        assert_eq!(text_parts, vec!["the answer".to_owned()]);
        assert!(scaffolding.is_empty());
    }

    /// `#519` follow-up: a wallet-link-needed turn with NO preceding real
    /// content gets exactly the deterministic shared-copy prompt, byte-
    /// identical to what `polyc_proto::wallet_link_prompt` produces — not
    /// something a caller must special-case, since `finalize_buffered_reply`
    /// decides it centrally for every buffered edge (Discord, email,
    /// trigger).
    #[test]
    fn finalize_buffered_reply_wallet_link_prompt_wins_with_url() {
        let url = "https://polychrome.example/link/abc";
        let reply = finalize_buffered_reply(
            &[],
            &[],
            WalletLinkPrompt::Present(Some(url.to_owned())),
            None,
        );
        assert_eq!(reply, polyc_proto::wallet_link_prompt(Some(url)));
        assert!(
            reply.contains(url),
            "the deterministic prompt carries the link: {reply}"
        );
    }

    #[test]
    fn finalize_buffered_reply_wallet_link_prompt_wins_without_url() {
        let reply = finalize_buffered_reply(&[], &[], WalletLinkPrompt::Present(None), None);
        assert_eq!(reply, polyc_proto::wallet_link_prompt(None));
    }

    /// Third-review finding: `text_parts` cannot be trusted as filtered,
    /// already-genuine content — `run_turn_with` dials the same
    /// `AgentService.connect` RPC as the streaming API, and the control plane
    /// forwards the harness's live `TextDelta`s to every client before the
    /// harness's post-hoc `internal_only` classification ever runs (and skips
    /// re-sending the filtered terminal batch once any delta was forwarded).
    /// So `text_parts` can hold the model's own raw, unfiltered wallet-link
    /// narration exactly like Slack/Telegram's live accumulator — a prior
    /// round's belief that appending was safe here was wrong. A
    /// wallet-link-needed turn must fully replace `text_parts`, matching
    /// Slack's `interrupt_holdback_text` and Telegram's reply-override.
    #[test]
    fn finalize_buffered_reply_wallet_link_prompt_replaces_preceding_content() {
        let url = "https://polychrome.example/link/abc";
        let reply = finalize_buffered_reply(
            &["It looks like you'll need to link a wallet first.".to_owned()],
            &[],
            WalletLinkPrompt::Present(Some(url.to_owned())),
            None,
        );
        assert_eq!(
            reply,
            polyc_proto::wallet_link_prompt(Some(url)),
            "preceding text_parts must not survive — it may be the model's own \
             unfiltered wallet-link narration, not genuine unrelated content: {reply}"
        );
    }

    /// A turn with no wallet-link signal is unaffected — the same
    /// text-then-scaffolding fallback behavior as before this change.
    #[test]
    fn finalize_buffered_reply_without_wallet_link_prompt_is_unchanged() {
        assert_eq!(
            finalize_buffered_reply(
                &["the answer".to_owned()],
                &[],
                WalletLinkPrompt::None,
                None
            ),
            "the answer"
        );
        assert_eq!(
            finalize_buffered_reply(
                &[],
                &["[tool_call:foo]".to_owned()],
                WalletLinkPrompt::None,
                None
            ),
            "[tool_call:foo]"
        );
        assert_eq!(
            finalize_buffered_reply(&[], &[], WalletLinkPrompt::None, None),
            ""
        );
    }

    /// PRD #767 sibling of `finalize_buffered_reply_wallet_link_prompt_wins_with_url`:
    /// a persona-credential mint with no preceding content gets exactly the
    /// deterministic shared-copy prompt.
    #[test]
    fn finalize_buffered_reply_persona_credential_prompt_wins() {
        let url = "https://wallet.polychrome.example/enroll-passkey?token=abc";
        let reply = finalize_buffered_reply(&[], &[], WalletLinkPrompt::None, Some(url));
        assert_eq!(reply, polyc_proto::persona_credential_prompt(Some(url)));
        assert!(
            reply.contains(url),
            "the deterministic prompt carries the link: {reply}"
        );
    }

    /// PRD #767 sibling of
    /// `finalize_buffered_reply_wallet_link_prompt_replaces_preceding_content`:
    /// a persona-credential mint REPLACES `text_parts` outright — it may hold
    /// the model's own raw, unfiltered narration of the same link (the
    /// identical live-delta hazard `finalize_buffered_reply`'s doc comment
    /// explains for wallet-link).
    #[test]
    fn finalize_buffered_reply_persona_credential_prompt_replaces_preceding_content() {
        let url = "https://wallet.polychrome.example/enroll-passkey?token=abc";
        let reply = finalize_buffered_reply(
            &["You can approve purchases faster by setting up a passkey.".to_owned()],
            &[],
            WalletLinkPrompt::None,
            Some(url),
        );
        assert_eq!(
            reply,
            polyc_proto::persona_credential_prompt(Some(url)),
            "preceding text_parts must not survive — it may be the model's own \
             unfiltered narration of the same link: {reply}"
        );
    }

    // --- streaming mapping (message_to_event) ---

    fn message(role: &str, ty: Option<content::Type>) -> Message {
        Message {
            role: role.to_owned(),
            content: buffa::MessageField::some(Content {
                r#type: ty,
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    #[test]
    fn assistant_text_becomes_text_delta() {
        assert_eq!(
            message_to_event(message("assistant", text("hello"))),
            Some(TurnEvent::TextDelta("hello".to_owned()))
        );
    }

    #[test]
    fn model_role_also_counts_as_assistant() {
        assert_eq!(
            message_to_event(message("model", text("hi"))),
            Some(TurnEvent::TextDelta("hi".to_owned()))
        );
    }

    #[test]
    fn tool_role_text_is_skipped() {
        // A tool-result echo carried as text must not surface as answer text.
        assert_eq!(message_to_event(message("tool", text("result blob"))), None);
    }

    #[test]
    fn empty_assistant_text_is_skipped() {
        assert_eq!(message_to_event(message("assistant", text(""))), None);
    }

    /// `#743`: an `internal_only` message — a paused turn's withheld model
    /// text, or an approver/policy note — must never surface as a streamed
    /// event, even though it carries otherwise-eligible assistant text.
    #[test]
    fn internal_only_assistant_text_is_skipped() {
        let mut msg = message("assistant", text("pending your approval"));
        msg.internal_only = true;
        assert_eq!(message_to_event(msg), None);
    }

    #[test]
    fn tool_call_becomes_tool_started_with_name() {
        assert_eq!(
            message_to_event(message("model", tool_call("call_7", "search"))),
            Some(TurnEvent::ToolStarted {
                name: "search".to_owned()
            })
        );
    }

    #[test]
    fn tool_call_falls_back_to_call_id() {
        assert_eq!(
            message_to_event(message(
                "tool",
                Some(content::Type::ToolCall(Box::new(ToolCallContent {
                    id: "call_bare".to_owned(),
                    r#type: None,
                    ..Default::default()
                })))
            )),
            Some(TurnEvent::ToolStarted {
                name: "call_bare".to_owned()
            })
        );
    }

    #[test]
    fn tool_result_produces_no_event() {
        assert_eq!(
            message_to_event(message("tool", tool_result("call_7"))),
            None
        );
    }

    // Drives the same per-message mapping the streaming loop uses, over a
    // synthetic turn, then appends Done as the End arm would.
    fn map_turn(msgs: Vec<Message>) -> Vec<TurnEvent> {
        let mut events: Vec<TurnEvent> = msgs.into_iter().filter_map(message_to_event).collect();
        events.push(TurnEvent::Done);
        events
    }

    #[test]
    fn synthetic_turn_yields_expected_event_sequence() {
        // model Text delta, a tool-role ToolCall, another model Text, End.
        let turn = vec![
            message("model", text("Let me look that up.")),
            message("tool", tool_call("call_1", "search")),
            message("model", text("Found it.")),
        ];
        assert_eq!(
            map_turn(turn),
            vec![
                TurnEvent::TextDelta("Let me look that up.".to_owned()),
                TurnEvent::ToolStarted {
                    name: "search".to_owned()
                },
                TurnEvent::TextDelta("Found it.".to_owned()),
                TurnEvent::Done,
            ]
        );
    }

    // --- terminal-envelope projection (events_from_end) ---

    use polyc_proto::proto::polychrome::agent::v1::{
        Handoff as WireHandoff, PendingApproval as WirePendingApproval,
    };

    #[test]
    fn end_with_nothing_yields_only_done() {
        assert_eq!(events_from_end(AgentEnd::default()), vec![TurnEvent::Done]);
    }

    #[test]
    fn end_with_handoff_yields_handoff_then_done() {
        let end = AgentEnd {
            handoff: buffa::MessageField::some(WireHandoff {
                call_id: "call_1".to_owned(),
                child_agent_id: "researcher".to_owned(),
                reason: "needs deep dive".to_owned(),
                ..Default::default()
            }),
            ..Default::default()
        };
        assert_eq!(
            events_from_end(end),
            vec![
                TurnEvent::HandoffStarted {
                    child_agent_id: "researcher".to_owned(),
                    reason: "needs deep dive".to_owned(),
                },
                TurnEvent::Done,
            ]
        );
    }

    #[test]
    fn end_orders_approvals_before_handoff_before_done() {
        let end = AgentEnd {
            pending_approvals: vec![WirePendingApproval {
                request_id: "r1".to_owned(),
                tool_name: "delete_file".to_owned(),
                args_json: "{}".to_owned(),
                title: "Delete a file".to_owned(),
                ..Default::default()
            }],
            handoff: buffa::MessageField::some(WireHandoff {
                child_agent_id: "child".to_owned(),
                ..Default::default()
            }),
            ..Default::default()
        };
        assert_eq!(
            events_from_end(end),
            vec![
                TurnEvent::ApprovalPending {
                    request_id: "r1".to_owned(),
                    tool_name: "delete_file".to_owned(),
                    title: "Delete a file".to_owned(),
                    args_json: "{}".to_owned(),
                    reason: String::new(),
                    resolve_token: String::new(),
                },
                TurnEvent::HandoffStarted {
                    child_agent_id: "child".to_owned(),
                    reason: String::new(),
                },
                TurnEvent::Done,
            ]
        );
    }

    #[test]
    fn end_projects_invite_deliveries_after_handoff_before_done() {
        use polyc_proto::proto::polychrome::agent::v1::InviteDelivery as WireInviteDelivery;
        let end = AgentEnd {
            invite_deliveries: vec![WireInviteDelivery {
                target_user_id: "UVITOR".to_owned(),
                code: "482913".to_owned(),
                inviter_display: "Ada".to_owned(),
                ..Default::default()
            }],
            ..Default::default()
        };
        assert_eq!(
            events_from_end(end),
            vec![
                TurnEvent::InviteDelivery {
                    target_user_id: "UVITOR".to_owned(),
                    code: "482913".to_owned(),
                    inviter_display: "Ada".to_owned(),
                },
                TurnEvent::Done,
            ]
        );
    }

    #[test]
    fn end_projects_wallet_link_prompt_after_invite_deliveries_before_done() {
        use polyc_proto::proto::polychrome::agent::v1::WalletLinkPrompt as WireWalletLinkPrompt;
        let end = AgentEnd {
            wallet_link_prompt: buffa::MessageField::some(WireWalletLinkPrompt {
                link_url: "https://polychrome.example/link/abc".to_owned(),
                ..Default::default()
            }),
            ..Default::default()
        };
        assert_eq!(
            events_from_end(end),
            vec![
                TurnEvent::WalletLinkPrompt {
                    link_url: Some("https://polychrome.example/link/abc".to_owned()),
                },
                TurnEvent::Done,
            ]
        );
    }

    #[test]
    fn end_projects_wallet_link_prompt_without_url_as_none() {
        use polyc_proto::proto::polychrome::agent::v1::WalletLinkPrompt as WireWalletLinkPrompt;
        let end = AgentEnd {
            wallet_link_prompt: buffa::MessageField::some(WireWalletLinkPrompt {
                link_url: String::new(),
                ..Default::default()
            }),
            ..Default::default()
        };
        assert_eq!(
            events_from_end(end),
            vec![
                TurnEvent::WalletLinkPrompt { link_url: None },
                TurnEvent::Done,
            ]
        );
    }

    #[test]
    fn end_projects_persona_credential_prompt_before_done() {
        use polyc_proto::proto::polychrome::agent::v1::PersonaCredentialPrompt as WirePersonaCredentialPrompt;
        let end = AgentEnd {
            persona_credential_prompt: buffa::MessageField::some(WirePersonaCredentialPrompt {
                link_url: "https://wallet.polychrome.example/enroll-passkey?token=abc".to_owned(),
                ..Default::default()
            }),
            ..Default::default()
        };
        assert_eq!(
            events_from_end(end),
            vec![
                TurnEvent::PersonaCredentialPrompt {
                    link_url: Some(
                        "https://wallet.polychrome.example/enroll-passkey?token=abc".to_owned()
                    ),
                },
                TurnEvent::Done,
            ]
        );
    }

    #[test]
    fn end_without_persona_credential_prompt_yields_only_done() {
        let end = AgentEnd::default();
        assert_eq!(events_from_end(end), vec![TurnEvent::Done]);
    }

    // --- namespaced conversation ids ---

    #[test]
    fn namespaced_id_is_prefix_colon_native() {
        assert_eq!(
            namespaced_id("mail", "CAF=abc@mail.example"),
            "mail:CAF=abc@mail.example"
        );
        assert_eq!(namespaced_id("web", "abc-123"), "web:abc-123");
    }

    #[test]
    fn enrollment_conversation_id_is_cron_routine_persona() {
        assert_eq!(
            enrollment_conversation_id("standup", "persona-9"),
            "cron:standup:persona-9"
        );
    }

    // Determinism: the same (routine, persona) always maps to the same
    // partition, so #621 (write) and #622 (read) agree without coordination.
    #[test]
    fn enrollment_conversation_id_is_deterministic() {
        for (routine, persona) in [
            ("standup", "persona-1"),
            ("weekly-digest", "abcdef01-2345-6789-abcd-ef0123456789"),
            ("", ""),
        ] {
            assert_eq!(
                enrollment_conversation_id(routine, persona),
                enrollment_conversation_id(routine, persona),
            );
        }
    }

    // Distinctness: a different routine OR a different principal yields a
    // different partition, so one principal's grant state never lands in
    // another's partition and two routines never share one.
    #[test]
    fn enrollment_conversation_id_is_distinct_per_routine_and_persona() {
        let base = enrollment_conversation_id("standup", "persona-1");
        assert_ne!(base, enrollment_conversation_id("standup", "persona-2"));
        assert_ne!(base, enrollment_conversation_id("digest", "persona-1"));
        assert_ne!(base, enrollment_conversation_id("digest", "persona-2"));
        // The two variable fields are separated, so swapping them cannot alias:
        // (routine=a, persona=b) is never (routine=b, persona=a).
        assert_ne!(
            enrollment_conversation_id("a", "b"),
            enrollment_conversation_id("b", "a"),
        );
    }

    // parse_enrollment_conversation_id is the exact inverse of the constructor
    // for every (routine, persona), and rejects a plain cron id so the two forms
    // are never confused.
    #[test]
    fn parse_enrollment_conversation_id_round_trips_and_rejects_plain_cron() {
        for (routine, persona) in [
            ("standup", "persona-1"),
            ("weekly-digest", "abcdef01-2345-6789-abcd-ef0123456789"),
        ] {
            let id = enrollment_conversation_id(routine, persona);
            assert_eq!(
                parse_enrollment_conversation_id(&id),
                Some((routine, persona)),
                "round-trips to its (routine, persona)"
            );
        }
        // A plain cron conversation id (two segments) is not an enrollment.
        assert_eq!(
            parse_enrollment_conversation_id("cron:nightly-report"),
            None
        );
        // A non-cron id is never an enrollment.
        assert_eq!(parse_enrollment_conversation_id("web:abc-123"), None);
        // Empty halves are rejected.
        assert_eq!(parse_enrollment_conversation_id("cron::persona"), None);
        assert_eq!(parse_enrollment_conversation_id("cron:standup:"), None);
    }

    // `enrollment_conversation_id` interpolates `routine` and `persona_id`
    // into the `"cron:{routine}:{persona}"` template by naive `format!`,
    // trusting that neither half ever carries a `:` — otherwise the id would
    // gain a spurious segment and `parse_enrollment_conversation_id` (the
    // round-trip inverse exercised above by
    // `parse_enrollment_conversation_id_round_trips_and_rejects_plain_cron`)
    // would split it wrong. That trust rests on two invariants enforced
    // upstream, not in this function: the routine name is a Kubernetes
    // `Routine.metadata.name`, so the CRD name grammar (a DNS-1123 subdomain,
    // mirrored in-repo by `controller::workflow_reconcile::is_label_fragment`
    // for the label-shaped subset) rejects `:` before the value ever reaches
    // here; the persona id is minted by `polyc_persona::new_provisional` as
    // `uuid::Uuid::now_v7().to_string()`, a hyphen-separated hex string that
    // never contains `:` either. This test pins the routine-name half of that
    // assumption: no string a DNS-1123 subdomain validator accepts can
    // contain `:`, over a representative sample (not every valid subdomain,
    // but enough shapes — single label, multi-label, digits, max-length-ish —
    // that a validator change reintroducing `:` acceptance would be caught).
    #[test]
    fn dns_1123_subdomain_names_never_contain_colon() {
        for name in [
            "standup",
            "weekly-digest",
            "a",
            "a1-b2",
            "sub.domain.example",
            "routine-123",
            "x.y.z",
            &"a".repeat(63),
        ] {
            assert!(
                is_dns_1123_subdomain(name),
                "`{name}` expected to be a valid DNS-1123 subdomain fixture"
            );
            assert!(
                !name.contains(':'),
                "DNS-1123 subdomain `{name}` must never contain ':'"
            );
        }
    }

    /// Minimal DNS-1123 subdomain check (RFC 1123, as Kubernetes applies it to
    /// object names): one or more '.'-separated labels, each lowercase
    /// alphanumeric or '-', starting and ending alphanumeric. `':'` is not in
    /// the alphabet, which is exactly the property
    /// `dns_1123_subdomain_names_never_contain_colon` pins.
    fn is_dns_1123_subdomain(name: &str) -> bool {
        !name.is_empty()
            && name.split('.').all(|label| {
                !label.is_empty()
                    && label.as_bytes()[0].is_ascii_lowercase()
                    && label.ends_with(|c: char| c.is_ascii_lowercase() || c.is_ascii_digit())
                    && label
                        .chars()
                        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
            })
    }

    #[test]
    fn hashed_conversation_id_is_deterministic_v5() {
        let ns = uuid::Uuid::from_u128(0x1234_5678_9abc_4def_8123_4567_89ab_cdef);
        let a = hashed_conversation_id(ns, &["T1", "C1", "169.000"]);
        let b = hashed_conversation_id(ns, &["T1", "C1", "169.000"]);
        assert_eq!(a, b);
        assert_ne!(a, hashed_conversation_id(ns, &["T1", "C2", "169.000"]));
        let parsed: uuid::Uuid = a.parse().unwrap();
        assert_eq!(parsed.get_version_num(), 5);
    }

    #[test]
    fn framed_conversation_id_resists_separator_collisions() {
        let ns = uuid::Uuid::from_u128(0x99);
        // The exact case that collides under the bare-join helper.
        assert_ne!(
            framed_conversation_id(ns, &["a:b", "c"]),
            framed_conversation_id(ns, &["a", "b:c"]),
        );
        // Sanity: the bare-join helper DOES collide here (documents why framed exists).
        assert_eq!(
            hashed_conversation_id(ns, &["a:b", "c"]),
            hashed_conversation_id(ns, &["a", "b:c"]),
        );
        // Deterministic + valid v5.
        let id = framed_conversation_id(ns, &["mail", "<abc@x>"]);
        assert_eq!(id, framed_conversation_id(ns, &["mail", "<abc@x>"]));
        assert_eq!(id.parse::<uuid::Uuid>().unwrap().get_version_num(), 5);
    }

    #[test]
    fn hashed_conversation_id_matches_slacks_inline_algorithm() {
        // Golden cross-check: the SDK helper must reproduce exactly what the
        // Slack edge used to compute inline (UUIDv5 of "team:channel:thread"
        // under a pinned namespace), so delegating in `polychrome-slack`
        // changes no existing conversation id.
        let ns = uuid::Uuid::from_u128(0xa1b2_c3d4_e5f6_4789_abcd_ef01_2345_6789);
        let parts = ["T01234ABCD", "C0000FAKEID", "1700000000.000100"];
        let inline = uuid::Uuid::new_v5(&ns, parts.join(":").as_bytes())
            .hyphenated()
            .to_string();
        assert_eq!(hashed_conversation_id(ns, &parts), inline);
    }

    #[test]
    fn link_outcome_messages_honor_presentation_rules() {
        // INVALID and EXPIRED are fused upstream into one variant, so neither
        // edge can distinguish them — one shared message, no oracle.
        assert!(
            LinkCeremony::InvalidOrExpired
                .user_message()
                .contains("invalid or expired")
        );
        // THROTTLED reads distinctly (wait, don't retry).
        assert!(LinkCeremony::Throttled.user_message().contains("wait"));
        assert!(
            LinkCeremony::Linked {
                persona_id: "p".to_owned()
            }
            .user_message()
            .contains("Linked")
        );
    }
}