aidaemon-tools 0.28.0

Ready-made tools for aidaemon agents (files, search, sandboxed shell, web, checklist); implementation crate of the aidaemon SDK, no stability promise (use it through aidaemon-sdk)
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
//! The semantic half of a daemon tool: plain data that describes a call
//! without executing it (capabilities, typed call semantics, access
//! manifests, receipt metadata, execution facts) and the helpers that derive
//! the conservative defaults.

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use aidaemon_core::ChannelVisibility;

/// The sender's role, shared across the SDK.
pub use aidaemon_core::UserRole;

/// Where an attachment originated — drives vision retention in archived turns.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum AttachmentProvenance {
    /// User sent via a channel (Telegram, Slack, Discord).
    #[default]
    Inbound,
    /// Produced by a tool observation (browser screenshot, MCP image, etc.).
    ToolObservation,
    /// Produced as a durable artifact by a tool (PDF, document, archive, etc.).
    ToolArtifact,
}

/// Metadata for a file saved from an inbound channel message or tool observation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct MessageAttachment {
    /// Stable opaque handle used by tools and policy. Legacy attachments omit
    /// it and receive one when they next cross the canonical event boundary.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource_id: Option<String>,
    pub local_path: String,
    pub filename: String,
    pub mime_type: String,
    pub size_bytes: u64,
    #[serde(default)]
    pub provenance: AttachmentProvenance,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_tool: Option<String>,
    /// Content digest captured when the attachment was registered. Execution
    /// re-checks this before sensitive use to detect stale/replaced files.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sha256: Option<String>,
    /// The owner drew marks over a picture to make this one: the unmarked
    /// picture's local path. The model is told the marks are the owner's.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub marked_up_from: Option<String>,
}

/// Categorization of a tool for role-based scoping.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolRole {
    /// Terminal, web_search, web_fetch, browser, etc.
    Action,
    /// ManageGoalTasksTool, ReportBlockerTool — task lead tools.
    Management,
    /// SystemInfoTool, RememberFactTool — available to all roles.
    Universal,
}

/// How a tool is offered to the model.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Offering {
    /// Sent on every call: without it the agent cannot do its everyday
    /// work (run commands, read and change files, reach the web, keep
    /// memory, schedule, track its checklist, delegate).
    Core,
    /// Exists only in a role-scoped run (a task's, a mandate run's or a
    /// coordinated child's own tools), where it is sent on every call.
    Scoped,
    /// Listed by name and one line in `load_tools`; its schema is sent once
    /// loaded (by `load_tools` or by calling it).
    #[default]
    Deferred,
}

impl Offering {
    /// Sent on every call where the tool is registered.
    pub fn always_sent(self) -> bool {
        matches!(self, Self::Core | Self::Scoped)
    }
}

/// Typed facts about how the dispatcher and the engine treat a tool. A tool
/// states them about itself; nothing keys on its name. Several can hold for
/// one tool, so they are flags beside [`ToolRole`] (which scopes tools by
/// agent role) rather than more roles.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ToolDispatchFacts {
    /// The kernel's approval rules judge this tool's calls in the canonical
    /// form the dispatcher executes, and the dispatcher then runs each call
    /// exactly as judged (the terminal).
    pub runs_as_judged: bool,
    /// The tool keeps the owner's answers to its cards in its own grant
    /// stores, consulted by its own ladder (the terminal's command
    /// prefixes), instead of the kernel's session grants.
    pub keeps_own_grants: bool,
    /// The call's `command` or `script` is a shell command line, which the
    /// kernel's access manifest carries so the approval policy's
    /// catastrophic-command check sees it (the terminal).
    pub shell_command_line: bool,
    /// Whether the tool's schema is sent on every model call
    /// ([`Offering::Core`]) or listed by name until the run loads it
    /// ([`Offering::Deferred`], the default).
    pub offering: Offering,
    /// A task lead keeps the tool through pruning: it is its delegation
    /// surface (`spawn_agent`, `cli_agent`, `manage_goal_tasks`).
    pub task_lead_delegation: bool,
    /// How long a run may call the tool consecutively before the
    /// same-tool guard treats it as a loop.
    pub same_tool_streak: SameToolStreak,
    /// The tool delivers a file to the user; the same file and caption go
    /// out once per task.
    pub delivers_files: bool,
    /// The tool spawns child agents, which inherit the turn's authority as
    /// it is when the call runs.
    pub spawns_child_agents: bool,
    /// The tool is the executor's requirement checklist: the status line
    /// shows the checklist, and its items become ledger expectations.
    pub requirement_checklist: bool,
    /// The call runs inside a process the daemon cannot see into (an MCP
    /// server), so its downstream effects escape per-action scoping and
    /// accounting. A mandate never delegates such a tool.
    pub opaque_execution: bool,
    /// The tool manages its own timeout and backgrounding, so the generic
    /// watchdog never wraps it (it would cancel the call early and could
    /// orphan the process it started).
    pub manages_own_timeout: bool,
    /// The tool records the trusted roots its launch was judged with (the
    /// terminal), so a background result keeps the trust it ran under.
    pub records_launch_trust: bool,
    /// Which goal facts the call receives.
    pub goal_context: GoalContext,
    /// Which addresses a call may name, judged by `web::NetworkGuard`.
    pub network_reach: NetworkReach,
    /// Which of a call's paths `ProtectedPathGuard` judges.
    pub file_guard: FileGuard,
    /// The dispatcher takes a file checkpoint before the call runs, so its
    /// writes can be rolled back.
    pub checkpoints_writes: bool,
    /// The call receives the live model, provider and model chain (a tool
    /// that runs its own model loop).
    pub needs_live_model: bool,
    /// The status line summarizes a finished call from its arguments, not
    /// its result (memory and people edits, whose result text is terse).
    pub status_from_arguments: bool,
    /// What a run's activity recap counts a finished call as.
    pub recap: RecapKind,
    /// What kind of work every card shows a call as.
    pub activity: ToolActivity,
    /// The words a live status ping uses for the tool ("reading a file").
    /// `None`: its name in words.
    pub status_label: Option<&'static str>,
    /// Which argument names the project directory a call works in, and how
    /// the turn's known project directory fills it when it is empty.
    pub project_dir_argument: ProjectDirArgument,
    /// The paths a call touches open their project's instructions on first
    /// access (reads, writes and command working directories; broad
    /// searches do not).
    pub opens_project_instructions: bool,
    /// How the engine fits the call's result for the model.
    pub result_fit: ResultFit,
    /// Which conversations the tool may be offered in.
    pub channel_reach: ChannelReach,
    /// What a substantive result from the call can serve as evidence for.
    pub evidence: EvidenceSource,
    /// The domain the tool inspects or changes, when it states no
    /// per-call semantics.
    pub semantic_scope: Option<ToolSemanticScope>,
    /// A result that says only that it worked (a write's confirmation):
    /// the turn's recent-work context leaves it out.
    pub low_signal_result: bool,
}

/// What a run's activity recap counts a finished call as (see
/// [`ToolDispatchFacts::recap`]).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum RecapKind {
    /// Counted only by what its summary says.
    #[default]
    Other,
    /// A file was read.
    FileRead,
    /// A file was written or edited.
    FileWrite,
    /// A command ran.
    Command,
    /// A file was sent to the user.
    FileSent,
    /// The web or the files were searched.
    Search,
    /// An external source was read.
    ExternalRead,
}

/// What kind of work a call is on every card (see
/// [`ToolDispatchFacts::activity`]).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ToolActivity {
    /// A check, or a change when the call's admitted semantics mutate.
    #[default]
    ByEffect,
    /// Always this kind.
    Fixed(aidaemon_core::card::ActivityKind),
    /// Memory: recalling when the call only reads, remembering when it
    /// changes what is kept.
    Memory,
}

impl ToolActivity {
    /// The kind a call of this tool shows as, given whether its admitted
    /// semantics mutate state.
    pub fn kind(self, mutates: bool) -> aidaemon_core::card::ActivityKind {
        use aidaemon_core::card::ActivityKind;
        match self {
            Self::Fixed(kind) => kind,
            Self::Memory if mutates => ActivityKind::Remember,
            Self::Memory => ActivityKind::Recall,
            Self::ByEffect if mutates => ActivityKind::Change,
            Self::ByEffect => ActivityKind::Check,
        }
    }
}

/// Which argument of a call names the directory it works in (see
/// [`ToolDispatchFacts::project_dir_argument`]).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ProjectDirArgument {
    /// Any path-like argument names a project directory; none is filled.
    #[default]
    AnyPath,
    /// The search root, `path`: filled with the known project directory.
    SearchRoot,
    /// The working directory, `working_dir`: filled with the known project
    /// directory, or its nearest existing parent when it is not made yet.
    WorkingDir,
    /// A shell: only `working_dir` or `cwd` names the directory (paths in
    /// the command are its data), filled as [`Self::WorkingDir`] and only
    /// when the call carries a command or script.
    ShellWorkingDir,
}

impl ProjectDirArgument {
    /// The argument the known project directory fills, if any.
    pub const fn injected_key(self) -> Option<&'static str> {
        match self {
            Self::AnyPath => None,
            Self::SearchRoot => Some("path"),
            Self::WorkingDir | Self::ShellWorkingDir => Some("working_dir"),
        }
    }
}

/// How the engine fits a call's result for the model (see
/// [`ToolDispatchFacts::result_fit`]).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ResultFit {
    /// The result is the model's working data and stays inline and whole,
    /// never spilled or compressed (the desktop's accessibility tree).
    pub preserve_inline: bool,
    /// A trusted result may carry the tool's internal control markers,
    /// stripped before the model sees it.
    pub strip_control_markers: bool,
    /// A large result is a structured API body, compacted losslessly.
    pub compact_json: bool,
    /// A large error is process output, cut to its head and tail.
    pub cap_large_errors: bool,
    /// The model can page through a spilled result with this tool, so an
    /// oversized result may be spilled to a file instead of compressed.
    pub pages_spilled_results: bool,
}

/// Which conversations a tool may be offered in (see
/// [`ToolDispatchFacts::channel_reach`]).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ChannelReach {
    /// Any conversation except a public external channel.
    #[default]
    Shared,
    /// Every conversation, a public external channel included.
    Public,
    /// It drives the owner's machine: only direct messages and internal
    /// sessions, never a shared or public channel.
    DirectOnly,
}

impl ChannelReach {
    /// Whether a tool of this reach may be offered in a conversation of
    /// `visibility`. The one rule for which tools a channel may see.
    pub fn offered_in(self, visibility: ChannelVisibility) -> bool {
        match self {
            Self::Public => true,
            Self::Shared => visibility != ChannelVisibility::PublicExternal,
            Self::DirectOnly => matches!(
                visibility,
                ChannelVisibility::Private | ChannelVisibility::Internal
            ),
        }
    }
}

/// What a substantive result from a tool can serve as evidence for, by the
/// kind of source it reads (see [`ToolDispatchFacts::evidence`]). The
/// capabilities each source supports live with the evidence ontology.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum EvidenceSource {
    /// No static evidence model: what the call supports is learnt from
    /// its result's own semantics.
    #[default]
    None,
    /// Goal and task forensics: a targeted trace, or a recent listing.
    GoalTrace,
    /// The owner's mandates, by action.
    Mandates,
    /// Goal tasks and automations: their state and record.
    GoalRecords,
    /// Past conversation.
    ConversationHistory,
    /// A remote page or API, read directly.
    RemoteRead,
    /// A connected node's readings.
    NodeReading,
    /// What a connected node did.
    NodeAction,
    /// A web search: advisory.
    WebSearch,
    /// A local file read.
    FileRead,
    /// A local file search.
    FileSearch,
    /// A local file edited in place: the edit read the file under its write
    /// fence and its result shows what the file now holds, so a successful
    /// one observes the file's current state as well as the write's outcome.
    FileWrite,
    /// A shell on this computer.
    Shell,
    /// This computer's state.
    HostInfo,
    /// The daemon's own diagnostics.
    Diagnostics,
}

impl EvidenceSource {
    /// Every source with an evidence model.
    pub const MODELED: [Self; 14] = [
        Self::GoalTrace,
        Self::Mandates,
        Self::GoalRecords,
        Self::ConversationHistory,
        Self::RemoteRead,
        Self::NodeReading,
        Self::NodeAction,
        Self::WebSearch,
        Self::FileRead,
        Self::FileSearch,
        Self::FileWrite,
        Self::Shell,
        Self::HostInfo,
        Self::Diagnostics,
    ];
}

/// Which of a tool's paths are judged against the secret and sensitive
/// patterns. A shell is not: the owner is asked about its commands instead.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum FileGuard {
    #[default]
    None,
    /// The paths it reads must not hold secrets.
    Reads,
    /// The paths it reads must not be sensitive (a superset of secrets, for
    /// a tool that publishes what it reads).
    SensitiveReads,
    /// The paths it changes must not be sensitive.
    Writes,
}

/// Which addresses a tool's egress may name. Cloud metadata endpoints are
/// refused for every tool, whatever this says.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum NetworkReach {
    /// Anything else, as a shell reaches the owner's own network.
    #[default]
    Any,
    /// Public hosts and this computer.
    PublicAndLoopback,
    /// Public hosts only.
    PublicOnly,
}

/// Which goal facts a call receives (see
/// [`ToolDispatchFacts::goal_context`]).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum GoalContext {
    /// None.
    #[default]
    None,
    /// The goal the run works for.
    Goal,
    /// The goal, found through the executor's task when the run carries
    /// only a task: the call's background notifications go to the goal's
    /// own session, since a child agent's session is not routable.
    BackgroundDelivery,
    /// The goal and, in a mandate run, the run's mandate fence (goal run,
    /// attempt, mandate and version).
    MandateRun,
}

/// The consecutive-call allowance of a tool (see
/// [`ToolDispatchFacts::same_tool_streak`]). Defined in the kernel so the
/// same-tool guard can take it without a dependency on the tools crate.
pub use aidaemon_core::SameToolStreak;

/// Safety and execution metadata for policy-driven tool selection.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolCapabilities {
    pub read_only: bool,
    pub external_side_effect: bool,
    pub needs_approval: bool,
    pub idempotent: bool,
    pub high_impact_write: bool,
}

/// Effect classification for a specific tool call.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum ToolCallEffect {
    #[default]
    Unknown,
    Administrative,
    Observation,
    Mutation,
    ObservationAndMutation,
}

/// Typed mutation effects for one tool call.
///
/// `ToolCallEffect` deliberately remains the compact observation/mutation
/// summary used by older persisted events. This set carries the detail needed
/// by policy and completion accounting so an incidental build-cache write does
/// not satisfy a requested source edit, and a local write does not satisfy a
/// requested remote deployment.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(transparent)]
pub struct ToolMutationEffects(u32);

impl ToolMutationEffects {
    pub const PROTOCOL_NAMES: [&str; 13] = [
        "local_source_write",
        "local_workspace_write",
        "local_derived_write",
        "repository_write",
        "remote_mutation",
        "remote_deploy",
        "external_delivery",
        "process_state",
        "configuration",
        "destructive",
        "unspecified",
        "scheduled_work",
        "memory_write",
    ];
    pub const NONE: Self = Self(0);
    /// A write to user-authored files through a path-aware editing tool.
    pub const LOCAL_SOURCE_WRITE: Self = Self(1 << 0);
    /// A local write whose target is not typed precisely (shell redirect,
    /// copy, generated file, and similar workspace activity).
    pub const LOCAL_WORKSPACE_WRITE: Self = Self(1 << 1);
    /// Compiler caches, dependency directories, and other reproducible output.
    pub const LOCAL_DERIVED_WRITE: Self = Self(1 << 2);
    /// Git refs, index state, commits, and related repository metadata.
    pub const REPOSITORY_WRITE: Self = Self(1 << 3);
    /// A remote state change that is not specifically a deployment.
    pub const REMOTE_MUTATION: Self = Self(1 << 4);
    /// Publishing a new application/site deployment or version.
    pub const REMOTE_DEPLOY: Self = Self(1 << 5);
    /// Sending, posting, uploading, or otherwise delivering content.
    pub const EXTERNAL_DELIVERY: Self = Self(1 << 6);
    /// Starting, stopping, restarting, or killing a process/service.
    pub const PROCESS_STATE: Self = Self(1 << 7);
    /// Mutating configuration, permissions, packages, or runtime setup.
    pub const CONFIGURATION: Self = Self(1 << 8);
    /// Deletion or another intentionally destructive local/remote operation.
    pub const DESTRUCTIVE: Self = Self(1 << 9);
    /// A command can mutate, but static inspection cannot state how. This is
    /// intentionally not allowed to satisfy a more specific required outcome.
    pub const UNSPECIFIED: Self = Self(1 << 10);
    /// Creating or changing the daemon's own goals, schedules and reminders.
    /// Nothing leaves the machine; the work it sets up is judged when it runs.
    pub const SCHEDULED_WORK: Self = Self(1 << 11);
    /// Saving to the daemon's own long-term memory. Nothing leaves the
    /// machine and no workspace file changes.
    pub const MEMORY_WRITE: Self = Self(1 << 12);

    /// Stable bit representation retained for durable telemetry and audits.
    /// Human-readable names are emitted alongside it; consumers must never
    /// interpret a raw bitset as a count.
    pub const fn bits(self) -> u32 {
        self.0
    }

    /// Rehydrate a durable effect set without interpreting the bits as a
    /// count. Unknown future bits remain visible to `telemetry_value` and do
    /// not silently become a known effect.
    pub const fn from_bits(bits: u32) -> Self {
        Self(bits)
    }

    /// Return the protocol names represented by this effect set. These names
    /// describe typed adapter effects, not natural-language task wording.
    pub fn protocol_names(self) -> Vec<&'static str> {
        [
            (Self::LOCAL_SOURCE_WRITE, "local_source_write"),
            (Self::LOCAL_WORKSPACE_WRITE, "local_workspace_write"),
            (Self::LOCAL_DERIVED_WRITE, "local_derived_write"),
            (Self::REPOSITORY_WRITE, "repository_write"),
            (Self::REMOTE_MUTATION, "remote_mutation"),
            (Self::REMOTE_DEPLOY, "remote_deploy"),
            (Self::EXTERNAL_DELIVERY, "external_delivery"),
            (Self::PROCESS_STATE, "process_state"),
            (Self::CONFIGURATION, "configuration"),
            (Self::DESTRUCTIVE, "destructive"),
            (Self::UNSPECIFIED, "unspecified"),
            (Self::SCHEDULED_WORK, "scheduled_work"),
            (Self::MEMORY_WRITE, "memory_write"),
        ]
        .into_iter()
        .filter_map(|(effect, name)| self.intersects(effect).then_some(name))
        .collect()
    }

    /// Machine-readable telemetry projection that keeps unknown future bits
    /// visible instead of silently dropping them.
    pub fn telemetry_value(self) -> serde_json::Value {
        let known_bits = Self::MEMORY_WRITE.bits()
            | Self::SCHEDULED_WORK.bits()
            | Self::UNSPECIFIED.bits()
            | ((1 << 10) - 1);
        serde_json::json!({
            "bits": self.bits(),
            "names": self.protocol_names(),
            "unknown_bits": self.bits() & !known_bits,
        })
    }

    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// Keep only effects present in both sets.  This is used when an adapter
    /// projects a task's typed obligation onto the subset it can actually
    /// report; it never interprets the bitset as a count.
    pub const fn intersect(self, other: Self) -> Self {
        Self(self.0 & other.0)
    }

    /// Parse a protocol enum value. These names are structured tool metadata,
    /// not natural-language routing keywords.
    pub fn from_protocol_name(name: &str) -> Option<Self> {
        match name {
            "local_source_write" => Some(Self::LOCAL_SOURCE_WRITE),
            "local_workspace_write" => Some(Self::LOCAL_WORKSPACE_WRITE),
            "local_derived_write" => Some(Self::LOCAL_DERIVED_WRITE),
            "repository_write" => Some(Self::REPOSITORY_WRITE),
            "remote_mutation" => Some(Self::REMOTE_MUTATION),
            "remote_deploy" => Some(Self::REMOTE_DEPLOY),
            "external_delivery" => Some(Self::EXTERNAL_DELIVERY),
            "process_state" => Some(Self::PROCESS_STATE),
            "configuration" => Some(Self::CONFIGURATION),
            "destructive" => Some(Self::DESTRUCTIVE),
            "unspecified" => Some(Self::UNSPECIFIED),
            "scheduled_work" => Some(Self::SCHEDULED_WORK),
            "memory_write" => Some(Self::MEMORY_WRITE),
            _ => None,
        }
    }

    pub const fn is_empty(&self) -> bool {
        self.0 == 0
    }

    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    pub const fn intersects(self, other: Self) -> bool {
        (self.0 & other.0) != 0
    }

    pub const fn has_specific_effects(self) -> bool {
        (self.0 & !Self::UNSPECIFIED.0) != 0
    }

    /// Whether observed effects fulfill every typed requirement.
    ///
    /// Known effects are checked strictly: cache output, repository metadata,
    /// and directory scaffolding cannot masquerade as authored source. Opaque
    /// execution surfaces report `UNSPECIFIED`, but unknown evidence is never
    /// allowed to prove a more specific effect. A caller that requires a source
    /// edit, deployment, or delivery must observe that exact typed effect.
    pub const fn satisfies(self, required: Self) -> bool {
        if required.is_empty() {
            return true;
        }
        let generic_required = required.intersects(Self::UNSPECIFIED);
        let generic_satisfied = !generic_required || !self.is_empty();
        let specific_required = Self(required.0 & !Self::UNSPECIFIED.0);
        // A precisely typed source write is also a workspace and a derived
        // write. Workspace and derived writes satisfy each other: the plan's
        // label is a hint, and the model cannot tell which one a tool
        // records (live 2026-11-18: a generated image, recorded as a
        // workspace write, never closed an item planned as a derived write,
        // and the closeout held a delivered reply for five model calls).
        // A source edit is still proven only by a source write.
        let widened = if self.intersects(Self::LOCAL_SOURCE_WRITE)
            || self.intersects(Self::LOCAL_DERIVED_WRITE)
            || self.intersects(Self::LOCAL_WORKSPACE_WRITE)
        {
            Self(self.0 | Self::LOCAL_WORKSPACE_WRITE.0 | Self::LOCAL_DERIVED_WRITE.0)
        } else {
            self
        };
        // A schedule is what a model means by `configuration` or
        // `process_state` when it plans one: the goal tools have nothing else
        // to report, so those plans must be able to close.
        let widened = if widened.intersects(Self::SCHEDULED_WORK) {
            Self(widened.0 | Self::CONFIGURATION.0 | Self::PROCESS_STATE.0)
        } else {
            widened
        };
        // A saved memory is what a model means by a derived write when it
        // plans one. Added after the workspace widening: it is not a file.
        let widened = if widened.intersects(Self::MEMORY_WRITE) {
            Self(widened.0 | Self::LOCAL_DERIVED_WRITE.0)
        } else {
            widened
        };
        generic_satisfied && widened.contains(specific_required)
    }
}

impl ToolCallEffect {
    pub fn observes_state(self) -> bool {
        matches!(self, Self::Observation | Self::ObservationAndMutation)
    }

    pub fn mutates_state(self) -> bool {
        matches!(self, Self::Mutation | Self::ObservationAndMutation)
    }
}

/// How a tool call can contribute verification evidence.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum ToolVerificationMode {
    #[default]
    None,
    ResultContent,
}

/// Typed target hint emitted by a tool call.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum ToolTargetHintKind {
    Url,
    Path,
    ProjectScope,
    /// Stable opaque identity from the session resource registry. Unlike a
    /// filename or prose reference this is exact, session-scoped, and safe to
    /// compare without natural-language interpretation.
    ResourceId,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolTargetHint {
    pub kind: ToolTargetHintKind,
    pub value: String,
}

impl ToolTargetHint {
    pub fn new(kind: ToolTargetHintKind, value: impl Into<String>) -> Option<Self> {
        let value = value.into().trim().to_string();
        if value.is_empty() {
            None
        } else {
            Some(Self { kind, value })
        }
    }
}

/// High-level domain a tool can inspect or mutate.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ToolSemanticScope {
    GoalState,
    UserMemory,
    ConversationHistory,
    ExternalRemote,
    LocalWorkspace,
    HostLocal,
}

impl ToolSemanticScope {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::GoalState => "goal_state",
            Self::UserMemory => "user_memory",
            Self::ConversationHistory => "conversation_history",
            Self::ExternalRemote => "external_remote",
            Self::LocalWorkspace => "local_workspace",
            Self::HostLocal => "host_local",
        }
    }
}

/// The kind of claim an observation can support. These are evidence roles,
/// not request-language keywords or tool names.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum EvidencePurpose {
    CurrentState,
    HistoricalRecord,
    Content,
    Outcome,
    Attribution,
    CausalExplanation,
}

impl EvidencePurpose {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::CurrentState => "current_state",
            Self::HistoricalRecord => "historical_record",
            Self::Content => "content",
            Self::Outcome => "outcome",
            Self::Attribution => "attribution",
            Self::CausalExplanation => "causal_explanation",
        }
    }
}

/// Strength of the source behind an observation.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceAuthority {
    /// A compressed memory, model-derived summary, or other discovery lead.
    Advisory,
    /// A direct observation of the resource being discussed.
    Direct,
    /// The daemon's authoritative ledger for the historical fact in question.
    Canonical,
}

impl EvidenceAuthority {
    const fn rank(self) -> u8 {
        match self {
            Self::Advisory => 0,
            Self::Direct => 1,
            Self::Canonical => 2,
        }
    }

    pub const fn satisfies(self, required: Self) -> bool {
        self.rank() >= required.rank()
    }

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Advisory => "advisory",
            Self::Direct => "direct",
            Self::Canonical => "canonical",
        }
    }
}

/// Time coverage of the subject records an observation surface can return.
/// Receipt timestamps independently prove when the observation itself ran; a
/// current query may therefore support historical subject data when the tool
/// exposes both current and historical records.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceTemporalScope {
    Current,
    Historical,
    Both,
}

impl EvidenceTemporalScope {
    pub const fn satisfies(self, required: Self) -> bool {
        matches!(required, Self::Both) && matches!(self, Self::Both)
            || matches!(required, Self::Current) && matches!(self, Self::Current | Self::Both)
            || matches!(required, Self::Historical) && matches!(self, Self::Historical | Self::Both)
    }

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Current => "current",
            Self::Historical => "historical",
            Self::Both => "both",
        }
    }
}

/// Claim-support metadata for one successful tool result. Unlike
/// [`ToolCapabilities`], this describes what information the result can prove,
/// not whether executing the tool is safe.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolEvidenceCapability {
    pub scope: ToolSemanticScope,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub purposes: Vec<EvidencePurpose>,
    pub authority: EvidenceAuthority,
    pub temporal_scope: EvidenceTemporalScope,
}

impl ToolEvidenceCapability {
    pub fn new(
        scope: ToolSemanticScope,
        purposes: &[EvidencePurpose],
        authority: EvidenceAuthority,
        temporal_scope: EvidenceTemporalScope,
    ) -> Self {
        Self {
            scope,
            purposes: purposes.to_vec(),
            authority,
            temporal_scope,
        }
    }
}

/// Fine-grained semantic capability advertised by a tool.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ToolSemanticFacet {
    /// Legacy coarse goal-state capability. New exact observations should use
    /// the narrow facet that was actually returned.
    GoalState,
    Schedule,
    RunState,
    Recovery,
    Control,
    Measurement,
    Authorization,
    Ownership,
}

impl ToolSemanticFacet {
    pub const PROTOCOL_NAMES: [&'static str; 8] = [
        Self::GoalState.as_str(),
        Self::Schedule.as_str(),
        Self::RunState.as_str(),
        Self::Recovery.as_str(),
        Self::Control.as_str(),
        Self::Measurement.as_str(),
        Self::Authorization.as_str(),
        Self::Ownership.as_str(),
    ];

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::GoalState => "goal_state",
            Self::Schedule => "schedule",
            Self::RunState => "run_state",
            Self::Recovery => "recovery",
            Self::Control => "control",
            Self::Measurement => "measurement",
            Self::Authorization => "authorization",
            Self::Ownership => "ownership",
        }
    }
}

/// Whether an adapter returned the whole requested collection. A truncated or
/// otherwise partial list may prove facts about the subjects it contains, but
/// it can never prove that another subject is absent.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ToolCollectionCompleteness {
    #[default]
    Unknown,
    Partial,
    Complete,
}

impl ToolCollectionCompleteness {
    pub const fn satisfies(self, required: Self) -> bool {
        matches!(required, Self::Unknown)
            || matches!(required, Self::Partial) && matches!(self, Self::Partial | Self::Complete)
            || matches!(required, Self::Complete) && matches!(self, Self::Complete)
    }
}

/// One exact subject/facet tuple observed in a successful tool result. This is
/// result evidence, not a capability prediction: adapters populate it only
/// after domain I/O has returned.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolObservationEvidence {
    pub subject: ToolTargetHint,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub facets: Vec<ToolSemanticFacet>,
    /// Collections from which this row was selected. Membership is lineage;
    /// absence still requires a separate complete collection observation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub source_collections: Vec<ToolTargetHint>,
}

impl ToolObservationEvidence {
    pub fn new(subject: ToolTargetHint, facets: &[ToolSemanticFacet]) -> Self {
        Self {
            subject,
            facets: facets.to_vec(),
            source_collections: Vec::new(),
        }
    }

    pub fn with_source_collection(mut self, collection: ToolTargetHint) -> Self {
        if !self.source_collections.contains(&collection) {
            self.source_collections.push(collection);
        }
        self
    }
}

/// Exact coverage of one collection returned by an adapter. `members` contains
/// stable identities, never display labels. Only `Complete` coverage can prove
/// non-membership; counts remain audit facts and are not interpreted as proof
/// on their own.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolCollectionObservation {
    pub collection: ToolTargetHint,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub facets: Vec<ToolSemanticFacet>,
    #[serde(default)]
    pub completeness: ToolCollectionCompleteness,
    #[serde(default)]
    pub returned_count: usize,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub total_count: Option<usize>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub members: Vec<ToolTargetHint>,
}

impl ToolCollectionObservation {
    pub fn complete(
        collection: ToolTargetHint,
        facets: &[ToolSemanticFacet],
        members: Vec<ToolTargetHint>,
    ) -> Self {
        let returned_count = members.len();
        Self {
            collection,
            facets: facets.to_vec(),
            completeness: ToolCollectionCompleteness::Complete,
            returned_count,
            total_count: Some(returned_count),
            members,
        }
    }
}

/// A receipt subject an adapter reports verbatim, published ahead of any call
/// so the executor's checklist can bind to identities that receipts will
/// actually carry. A checklist target outside every advertised subject and
/// member namespace can never be credited, so the checklist tool refuses to
/// compile it into an exact obligation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct StableObservationSubject {
    /// Exact `ResourceId` the adapter reports for a fixed collection or
    /// singleton subject, when that identity is known before the call.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource_id: Option<String>,
    /// Facets a receipt for this subject or its members can carry.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub facets: Vec<ToolSemanticFacet>,
    /// `ResourceId` prefixes of exact member identities the adapter or the
    /// runtime mints (for example `auth_profile:`). A value under a prefix is
    /// exact and is credited only by a receipt naming it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub member_namespaces: Vec<String>,
    /// Short model-facing meaning of the subject.
    pub summary: String,
}

impl StableObservationSubject {
    pub fn collection(
        resource_id: impl Into<String>,
        facets: &[ToolSemanticFacet],
        member_namespace: impl Into<String>,
        summary: impl Into<String>,
    ) -> Self {
        Self {
            resource_id: Some(resource_id.into()),
            facets: facets.to_vec(),
            member_namespaces: vec![member_namespace.into()],
            summary: summary.into(),
        }
    }

    pub fn namespace(prefix: impl Into<String>, summary: impl Into<String>) -> Self {
        Self {
            resource_id: None,
            facets: Vec::new(),
            member_namespaces: vec![prefix.into()],
            summary: summary.into(),
        }
    }

    /// Whether `value` is this subject itself or an exact member under one of
    /// its namespaces. A bare prefix with nothing after it is not a member.
    pub fn binds(&self, value: &str) -> bool {
        self.resource_id.as_deref() == Some(value)
            || self
                .member_namespaces
                .iter()
                .any(|prefix| value.len() > prefix.len() && value.starts_with(prefix.as_str()))
    }
}

/// Canonical adapter operation used by deterministic operation-scoped policy.
/// Unknown/new HTTP verbs deliberately remain untyped and therefore cannot
/// match a delegated mandate scope.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "UPPERCASE")]
pub enum ToolCallOperation {
    Get,
    Head,
    Options,
    Post,
    Put,
    Patch,
    Delete,
}

impl ToolCallOperation {
    pub const fn from_http_method(method: &str) -> Option<Self> {
        match method.as_bytes() {
            b"GET" => Some(Self::Get),
            b"HEAD" => Some(Self::Head),
            b"OPTIONS" => Some(Self::Options),
            b"POST" => Some(Self::Post),
            b"PUT" => Some(Self::Put),
            b"PATCH" => Some(Self::Patch),
            b"DELETE" => Some(Self::Delete),
            _ => None,
        }
    }
}

/// Structured completion semantics for a specific tool call.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ToolCallSemantics {
    #[serde(default)]
    pub effect: ToolCallEffect,
    #[serde(default)]
    pub verification_mode: ToolVerificationMode,
    /// Fine-grained mutation effects. Older persisted rows omit this field and
    /// continue to deserialize through the default empty set.
    #[serde(default, skip_serializing_if = "ToolMutationEffects::is_empty")]
    pub mutation_effects: ToolMutationEffects,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub target_hints: Vec<ToolTargetHint>,
    /// Adapter-defined canonical operation for policy matching. This is an
    /// exact, typed identifier (for example `GET` or `POST`), not a natural-
    /// language action inferred by the policy layer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operation: Option<ToolCallOperation>,
    /// Typed claim-support affordances for this exact call/result. These are
    /// persisted in the durable receipt so recovery and completion do not have
    /// to reconstruct evidence from prose.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence: Vec<ToolEvidenceCapability>,
}

/// Prepared filesystem access requested by one exact tool call.
///
/// Execution location, readable context, and mutation authority are different
/// roles. Keeping them separate prevents a read-only working directory from
/// becoming an implied write grant and gives adapters one canonical contract
/// to enforce and persist.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolCallAccessManifest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub execution_cwd: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub read_targets: Vec<ToolTargetHint>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub write_targets: Vec<ToolTargetHint>,
    /// Immutable capabilities owned by the adapter itself (for example the
    /// system executable roots a confined terminal needs to start a process).
    /// These are deliberately separate from task data grants: callers may use
    /// them for runtime loading, but they do not authorize arbitrary user
    /// paths or writes and are never inferred from command prose.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub adapter_read_targets: Vec<ToolTargetHint>,
}

impl ToolCallSemantics {
    /// These semantics plus a change static inspection cannot type: still
    /// the observation they were, now also a mutation (`UNSPECIFIED`, which
    /// proves only the checklist items the call carries out).
    pub fn with_untyped_change(&self) -> Self {
        let mut changed = self.clone();
        changed.mutation_effects = changed
            .mutation_effects
            .union(ToolMutationEffects::UNSPECIFIED);
        changed.effect = if changed.observes_state() {
            ToolCallEffect::ObservationAndMutation
        } else {
            ToolCallEffect::Mutation
        };
        changed
    }

    pub fn administrative() -> Self {
        Self {
            effect: ToolCallEffect::Administrative,
            ..Self::default()
        }
    }

    pub fn observation() -> Self {
        Self {
            effect: ToolCallEffect::Observation,
            ..Self::default()
        }
    }

    pub fn mutation() -> Self {
        Self {
            effect: ToolCallEffect::Mutation,
            mutation_effects: ToolMutationEffects::UNSPECIFIED,
            ..Self::default()
        }
    }

    pub fn observation_and_mutation() -> Self {
        Self {
            effect: ToolCallEffect::ObservationAndMutation,
            mutation_effects: ToolMutationEffects::UNSPECIFIED,
            ..Self::default()
        }
    }

    pub fn mutation_with(mutation_effects: ToolMutationEffects) -> Self {
        Self {
            effect: ToolCallEffect::Mutation,
            mutation_effects: if mutation_effects.is_empty() {
                ToolMutationEffects::UNSPECIFIED
            } else {
                mutation_effects
            },
            ..Self::default()
        }
    }

    pub fn observation_and_mutation_with(mutation_effects: ToolMutationEffects) -> Self {
        Self {
            effect: ToolCallEffect::ObservationAndMutation,
            mutation_effects: if mutation_effects.is_empty() {
                ToolMutationEffects::UNSPECIFIED
            } else {
                mutation_effects
            },
            ..Self::default()
        }
    }

    pub fn with_verification_mode(mut self, verification_mode: ToolVerificationMode) -> Self {
        self.verification_mode = verification_mode;
        self
    }

    pub fn with_target_hint(mut self, kind: ToolTargetHintKind, value: impl Into<String>) -> Self {
        if let Some(target) = ToolTargetHint::new(kind, value) {
            self.target_hints.push(target);
        }
        self
    }

    pub fn with_operation(mut self, operation: ToolCallOperation) -> Self {
        self.operation = Some(operation);
        self
    }

    pub fn with_evidence(mut self, evidence: Vec<ToolEvidenceCapability>) -> Self {
        self.evidence = evidence;
        self
    }

    pub fn observes_state(&self) -> bool {
        self.effect.observes_state()
    }

    pub fn mutates_state(&self) -> bool {
        self.effect.mutates_state() || !self.mutation_effects.is_empty()
    }

    pub fn can_verify_with_result_content(&self) -> bool {
        self.verification_mode == ToolVerificationMode::ResultContent
    }

    pub fn is_empty(&self) -> bool {
        self.effect == ToolCallEffect::Unknown
            && self.verification_mode == ToolVerificationMode::None
            && self.mutation_effects.is_empty()
            && self.target_hints.is_empty()
            && self.operation.is_none()
            && self.evidence.is_empty()
    }

    pub fn merge_missing_from(&mut self, fallback: Self) {
        if self.effect == ToolCallEffect::Unknown {
            self.effect = fallback.effect;
        }
        if self.verification_mode == ToolVerificationMode::None {
            self.verification_mode = fallback.verification_mode;
        }
        // An explicit observational effect is authoritative. Filling its empty
        // mutation bitset from a conservative pre-dispatch fallback would turn
        // a tool-enforced read-only execution back into a mutation receipt.
        if self.mutation_effects.is_empty()
            && (self.effect == ToolCallEffect::Unknown || self.effect.mutates_state())
        {
            self.mutation_effects = fallback.mutation_effects;
        }
        if self.target_hints.is_empty() {
            self.target_hints = fallback.target_hints;
        }
        if self.operation.is_none() {
            self.operation = fallback.operation;
        }
        if self.evidence.is_empty() {
            self.evidence = fallback.evidence;
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ReadFileSelectionMetadata {
    Full,
    BoundedRange { start_line: usize, end_line: usize },
    OpenEndedRange { start_line: usize },
    Tail { requested_lines: usize },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ReadFileResultMetadata {
    pub display_path: String,
    pub canonical_path: String,
    pub selection: ReadFileSelectionMetadata,
    pub returned_start_line: Option<usize>,
    pub returned_end_line: Option<usize>,
    pub total_lines: usize,
    pub file_size: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified: Option<String>,
    pub selected_lines: Vec<String>,
    /// True when the read returned fewer lines than requested because the
    /// per-call output cap was hit. The rendered output then carries an
    /// explicit continuation hint.
    #[serde(default)]
    pub truncated: bool,
}

/// Structured record of tool-output truncation. Populated at the tool
/// boundary — the instructional notice text is rendered into the
/// model-visible message by the loop (single site), never embedded in the
/// tool's returned content, so text-scanning consumers (error-line
/// extraction, classifiers, summaries) always see clean output.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TruncationInfo {
    pub shown_chars: usize,
    pub total_chars: usize,
    /// Tool-specific remediation sentence (see `utils::truncation_notice_with_hint`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub remediation_hint: Option<String>,
}

/// Whether a particular retained view contains the authoritative tool result.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum ToolResultCompleteness {
    Complete,
    Truncated,
    #[default]
    Unavailable,
}

impl ToolResultCompleteness {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Complete => "complete",
            Self::Truncated => "truncated",
            Self::Unavailable => "unavailable",
        }
    }
}

/// Origin of the bytes represented by a durable observation receipt.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum ToolResultContentSource {
    ToolOutput,
    DurableReplay,
    SpillPreview,
    PersistentSummary,
    #[default]
    Unavailable,
}

impl ToolResultContentSource {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ToolOutput => "tool_output",
            Self::DurableReplay => "durable_replay",
            Self::SpillPreview => "spill_preview",
            Self::PersistentSummary => "persistent_summary",
            Self::Unavailable => "unavailable",
        }
    }
}

/// Content provenance shared by live completion and durable continuation.
/// The digest is computed over the authoritative pre-compression result; the
/// view-specific fields state exactly what the model and event log retained.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ToolResultProvenance {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sha256: Option<String>,
    #[serde(default)]
    pub source: ToolResultContentSource,
    #[serde(default)]
    pub model_view_completeness: ToolResultCompleteness,
    #[serde(default)]
    pub durable_view_completeness: ToolResultCompleteness,
    #[serde(default)]
    pub authoritative_chars: usize,
    #[serde(default)]
    pub model_visible_chars: usize,
    #[serde(default)]
    pub durable_chars: usize,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requested_range: Option<ReadFileSelectionMetadata>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub returned_start_line: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub returned_end_line: Option<usize>,
}

/// Deterministic credential/target readiness checked immediately before an
/// autonomous adapter is allowed to perform I/O. The accompanying durable
/// receipt carries the mandate grant, which binds this record to the stable
/// mandate identity and policy version without exposing credentials.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AuthorizationPreflightStatus {
    Ready,
    Blocked,
    Unverifiable,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AuthorizationPreflightRecord {
    pub schema_version: u16,
    pub status: AuthorizationPreflightStatus,
    pub intended_operation: String,
    pub target_digest: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth_profile: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub account_id: Option<String>,
    /// Provider-declared OAuth scopes known at the readiness boundary. Static
    /// non-OAuth profiles legitimately leave this empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub authorized_scopes: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub credential_generation: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refresh_result: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason_code: Option<String>,
    pub checked_at: String,
}

impl AuthorizationPreflightRecord {
    pub const SCHEMA_VERSION: u16 = 1;

    pub const fn permits_io(&self) -> bool {
        matches!(self.status, AuthorizationPreflightStatus::Ready)
    }
}

impl ToolResultProvenance {
    pub fn from_authoritative_result(
        result: &str,
        metadata: &ToolCallMetadata,
        source: ToolResultContentSource,
    ) -> Self {
        use sha2::{Digest, Sha256};

        let sha256 = hex::encode(Sha256::digest(result.as_bytes()));
        let chars = result.chars().count();
        let tool_truncated = metadata.truncation.is_some()
            || metadata
                .read_file
                .as_ref()
                .is_some_and(|read| read.truncated);
        let completeness = if tool_truncated {
            ToolResultCompleteness::Truncated
        } else {
            ToolResultCompleteness::Complete
        };
        let read = metadata.read_file.as_ref();
        Self {
            result_id: Some(format!("sha256:{sha256}")),
            sha256: Some(sha256),
            source,
            model_view_completeness: completeness,
            durable_view_completeness: completeness,
            authoritative_chars: chars,
            model_visible_chars: chars,
            durable_chars: chars,
            requested_range: read.map(|read| read.selection.clone()),
            returned_start_line: read.and_then(|read| read.returned_start_line),
            returned_end_line: read.and_then(|read| read.returned_end_line),
        }
    }

    pub fn mark_model_view_truncated(&mut self, visible_result: &str) {
        self.model_visible_chars = visible_result.chars().count();
        self.model_view_completeness = ToolResultCompleteness::Truncated;
    }

    pub fn record_durable_view(&mut self, durable_result: &str, is_summary: bool) {
        self.durable_chars = durable_result.chars().count();
        if is_summary {
            self.durable_view_completeness = ToolResultCompleteness::Truncated;
            self.source = ToolResultContentSource::PersistentSummary;
        } else {
            self.durable_view_completeness = self.model_view_completeness;
        }
    }
}

/// Structured outcome of a tool invocation. This separates transport/execution
/// success from the domain result: a test runner can execute correctly while
/// reporting failing tests, and a lookup can complete with no matches.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolOutcomeStatus {
    Succeeded,
    CompletedWithNegativeResult,
    FailedRetryable,
    FailedPermanent,
    Blocked,
    Backgrounded,
}

/// Where an invocation reached in the common execution pipeline.
///
/// This is deliberately orthogonal to [`ToolOutcomeStatus`]. A deterministic
/// argument rejection can be a completed validation observation, but it did
/// not dispatch the requested domain operation and therefore cannot inherit
/// that operation's effects, targets, or evidence capabilities.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolInvocationStage {
    /// Legacy receipt or adapter that did not report a stage.
    #[default]
    Unknown,
    /// The common policy/retry boundary refused dispatch.
    RejectedBeforeDispatch,
    /// The adapter rejected its typed argument contract before domain I/O.
    RejectedBeforeIo,
    /// The adapter was invoked for the prepared operation.
    Dispatched,
    /// The result was reconstructed from a durable prior receipt.
    Replayed,
}

impl ToolInvocationStage {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Unknown => "unknown",
            Self::RejectedBeforeDispatch => "rejected_before_dispatch",
            Self::RejectedBeforeIo => "rejected_before_io",
            Self::Dispatched => "dispatched",
            Self::Replayed => "replayed",
        }
    }

    pub const fn reached_dispatch(self) -> bool {
        matches!(self, Self::Dispatched | Self::Replayed)
    }

    /// True only for a newly executed adapter call. A durable replay carries
    /// evidence forward but does not consume another operation attempt.
    pub const fn performed_io(self) -> bool {
        matches!(self, Self::Dispatched)
    }
}

/// Shape of the machine receipt produced by a tool invocation.
///
/// Completion predicates are compiled against this protocol type instead of
/// assuming every tool is a subprocess. In particular, an absent exit code on
/// a management/API receipt means "not applicable", not "the invocation did
/// not happen".
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolReceiptKind {
    #[default]
    Generic,
    Process,
    Http,
}

/// Strength of the boundary that enforced a tool's declared filesystem
/// manifest. This reports enforcement, not merely manifest presence.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolAccessEnforcement {
    /// Legacy or uninstrumented adapter; no enforcement claim is made.
    #[default]
    Unknown,
    /// The operation has no filesystem access contract.
    NotApplicable,
    /// A delegated sandbox adapter accepted the manifest.
    AdapterEnforced,
    /// The daemon controller rejected the proposal before adapter dispatch
    /// because it exceeded the compiled task capability.
    ControllerEnforced,
    /// The daemon installed a kernel-enforced policy from the exact manifest.
    KernelEnforced,
}

/// Typed diagnostic emitted when a proposal is rejected by the controller or
/// an adapter is denied by its installed filesystem policy. This is audit
/// telemetry only; the manifest remains the authority and this record never
/// widens it.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolAccessDenial {
    pub reason_code: String,
    pub enforcement: ToolAccessEnforcement,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    /// Evidence the refused operation WOULD have produced. A rejection
    /// receipt carries no observed evidence (nothing ran), but the run ledger
    /// needs to know which observation obligation the refusal was attempting
    /// to satisfy; that binding is proposal data, typed on the denial.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub proposed_evidence: Vec<ToolEvidenceCapability>,
}

impl ToolOutcomeStatus {
    /// Normalize the execution backend's process status convention. Unix
    /// commands that exit normally produce a nonnegative code; the backend
    /// uses a negative sentinel when no normal exit status exists (for
    /// example, a sandbox kill). Such termination is not a completed negative
    /// predicate observation.
    pub const fn from_process_exit_code(code: i32) -> Self {
        if code == 0 {
            Self::Succeeded
        } else if code > 0 {
            Self::CompletedWithNegativeResult
        } else {
            Self::FailedPermanent
        }
    }

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Succeeded => "succeeded",
            Self::CompletedWithNegativeResult => "completed_with_negative_result",
            Self::FailedRetryable => "failed_retryable",
            Self::FailedPermanent => "failed_permanent",
            Self::Blocked => "blocked",
            Self::Backgrounded => "backgrounded",
        }
    }

    pub fn satisfies_requested_condition(self) -> bool {
        matches!(self, Self::Succeeded)
    }

    pub fn is_failure(self) -> bool {
        matches!(
            self,
            Self::FailedRetryable | Self::FailedPermanent | Self::Blocked
        )
    }
}

/// How the response layer should treat a successful tool result.
///
/// This is control-plane metadata, not a canned user response. Tools use it to
/// distinguish an owner-facing operational outcome from an explicitly
/// requested diagnostic view while leaving the wording to the model.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolResultPresentation {
    NaturalSummary,
    DiagnosticDetail,
}

/// Structured execution metadata returned by tools.
///
/// This is intentionally minimal and backward-compatible: tools can continue
/// returning plain text while selectively populating structured fields.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolCallMetadata {
    /// Protocol family for fields whose applicability differs by adapter.
    /// The dispatcher stamps this from the registered tool before completion
    /// evaluation; tools do not need to repeat the declaration per result.
    #[serde(default)]
    pub receipt_kind: ToolReceiptKind,
    /// Effective filesystem access contract enforced for this invocation.
    /// This is an audit receipt, not a reusable authority grant.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub access_manifest: Option<ToolCallAccessManifest>,
    /// Whether the declared access manifest was installed at an execution
    /// boundary. A populated manifest with `Unknown` is audit data only.
    #[serde(default)]
    pub access_enforcement: ToolAccessEnforcement,
    /// Kernel/adapter denial details when a dispatched process was prevented
    /// from opening a path. The declared manifest is retained separately.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub access_denial: Option<ToolAccessDenial>,
    /// Authoritative domain outcome when the tool can provide one. Older tools
    /// may omit it; the loop then derives a conservative status from structured
    /// exit/HTTP/transport metadata before falling back to legacy text parsing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub outcome_status: Option<ToolOutcomeStatus>,
    /// Authoritative pipeline stage for this result. Completion and effect
    /// projection must never infer dispatch from intended call semantics.
    #[serde(default)]
    pub invocation_stage: ToolInvocationStage,
    /// The adapter deterministically rejected the invocation contract before
    /// performing domain I/O. This is an authoritative negative outcome, not
    /// evidence that the requested read/write itself occurred.
    #[serde(default)]
    pub contract_rejected: bool,
    /// Actual adapter that produced the result when dispatch was routed from
    /// the requested tool through another implementation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effective_tool_name: Option<String>,
    /// True when the dispatcher reconstructed this outcome from a prior
    /// durable receipt instead of invoking the side effect again.
    #[serde(default)]
    pub receipt_replayed: bool,
    /// Process exit code when applicable (e.g. terminal/run_command style tools).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    /// True when tool execution exceeded a timeout threshold.
    #[serde(default)]
    pub timed_out: bool,
    /// True when execution moved to background tracking.
    #[serde(default)]
    pub background_started: bool,
    /// True when the process is detached and intentionally long-lived.
    #[serde(default)]
    pub detached: bool,
    /// True when the tool guarantees automatic completion delivery for a
    /// backgrounded operation in the current run.
    #[serde(default)]
    pub completion_notifications_enabled: bool,
    /// Transport/runtime failure outside normal tool semantics.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transport_error: Option<String>,
    /// HTTP status code for API tools (http_request, web_fetch).
    /// Populated at the tool boundary — not scraped from result text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub http_status: Option<u16>,
    /// Canonical id of the resource a successful write created, read by the
    /// adapter from the response's machine format (JSON `/data/id` or `/id`)
    /// and validated as `[A-Za-z0-9_-]{1,64}`. Never model or prose text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created_resource_id: Option<String>,
    /// Output truncation performed at the tool boundary. Rendered into the
    /// model-visible text by the loop after ledger/classifier consumption.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub truncation: Option<TruncationInfo>,
    /// Strong provenance for the result body. Populated centrally by the tool
    /// dispatcher so individual adapters cannot silently omit it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result_provenance: Option<ToolResultProvenance>,
    /// Exact pre-I/O authorization readiness for autonomous authenticated
    /// adapters. It is persisted with the receipt and never contains secrets.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub authorization_preflight: Option<AuthorizationPreflightRecord>,
    /// The call handed the rest of the turn's work to a background job whose
    /// result reaches the session later (a launch moved to background
    /// tracking, a background sub-agent). Set with the call's finish by
    /// [`ToolCallOutcome::handed_to_background`]; unlike
    /// `background_started` it says nothing about the receipt's status.
    #[serde(default)]
    pub background_handoff: bool,
    /// The call observed the end of a background job a launch left running
    /// (a check that returned its finished result, or a cancel). The run
    /// pairs it with `background_started` launches to know whether work it
    /// handed off is still running when the model wants to stop.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub background_settled: bool,
    /// The names, as the owner reads them, of the runs this call left
    /// running in the background (a helper, a command, a CLI agent; every
    /// child of a batch call, in order): the turn's launch line names its
    /// runs from these, never from the call's text (live 2026-11-14: a
    /// batch of two named only its first child).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub background_run_labels: Vec<String>,
    /// The declared checklist items (their indices) this call took on: a
    /// launch hands them to the job it starts (`checklist_items`). Typed
    /// attribution of work to declared items, never read from text.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub checklist_items: Vec<usize>,
    /// How many runs this call launched, still working when it returned or
    /// run to their end within it (a batch launch starts one per child).
    /// Each run takes on its own work: a launch of two helpers that names no
    /// items is two attempts, never one. One run that names no items and
    /// ends within the call took on the whole request.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub launched_runs: usize,
    /// The call changed something its semantics could not type (a write
    /// inside `docker exec` or `ssh`, judged from the command's structure):
    /// the runtime may attribute it to the one checklist item in progress.
    /// Never itself a typed change.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub changes_untyped: bool,
    /// Completion semantics for this specific tool call.
    #[serde(default, skip_serializing_if = "ToolCallSemantics::is_empty")]
    pub semantics: ToolCallSemantics,
    /// Exact subject/facet observations made by this dispatched result. These
    /// are intentionally separate from `ToolCallSemantics`: proposed call
    /// semantics must never become proof merely because dispatch was planned.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub observations: Vec<ToolObservationEvidence>,
    /// Collection membership and coverage observed by this dispatched result.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub collection_observations: Vec<ToolCollectionObservation>,
    /// Complete typed result for successful text-file reads.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub read_file: Option<ReadFileResultMetadata>,
    /// Image (or other) files produced by the tool for agent vision context.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attachments: Vec<MessageAttachment>,
    /// The runtime's own pre-dispatch preparation failed (for example
    /// materializing a declared write root), attributed to the exact argument
    /// declaration that caused it. Set only when no domain I/O ran.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime_preparation_failure: Option<Box<RuntimePreparationFailure>>,
    /// Preserve exact, untrusted bytes while still wrapping them as untrusted
    /// tool data. Intended for canonical-history evidence whose wording must
    /// not be rewritten by prompt-injection sanitization.
    #[serde(default)]
    pub untrusted_verbatim: bool,
    /// Keep bounded tool output inline and never write it to a temporary spill
    /// file or run lossy generic compression.
    #[serde(default)]
    pub preserve_inline: bool,
    /// Durable audit representation. The full output remains available to the
    /// current model turn, but only this stub is written to canonical events.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub persistent_output: Option<String>,
    /// Do not copy result content into executor task-activity telemetry.
    #[serde(default)]
    pub suppress_activity_result: bool,
    /// Presentation policy for this result. `NaturalSummary` asks the response
    /// layer to communicate the user-level outcome without exposing control-
    /// plane bookkeeping. `DiagnosticDetail` is selected only when the caller
    /// explicitly requested those details.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub presentation: Option<ToolResultPresentation>,
    /// Exact control-plane identifiers observed by the tool. They remain
    /// available to the agent/runtime but are omitted from a natural summary
    /// unless the owner supplied the same identifier or requested diagnostics.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub internal_identifiers: Vec<String>,
    /// Who authored this exact output, when the tool knows better than its
    /// declared `Tool::output_trust` (a delegated run reports whether it read
    /// untrusted content). The dispatcher stamps this over the declaration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output_trust: Option<aidaemon_core::SourceTrust>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolCallOutcome {
    pub output: String,
    #[serde(default)]
    pub metadata: ToolCallMetadata,
    /// The tool ends the run on this call, from its own typed outcome (never
    /// from argument or output text). The dispatcher hands it to the kernel
    /// as [`aidaemon_core::ToolOutput::finish`]; a finish without a reply
    /// ships the call's own output.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub finish: Option<aidaemon_core::Finish>,
}

/// A failure of the runtime's own pre-dispatch preparation, attributed to the
/// exact argument declaration that caused it. The dispatcher uses this to
/// decide whether the declaration was its own projection (repairable without
/// involving the model) or the model's (surfaced as a typed rejection).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RuntimePreparationFailure {
    /// Argument field the declaration came from (for example `write_roots`).
    pub field: String,
    /// The exact declared value.
    pub value: String,
    /// The underlying runtime error.
    pub error: String,
}

impl ToolCallOutcome {
    pub fn from_output(output: String) -> Self {
        Self {
            output,
            metadata: ToolCallMetadata::default(),
            finish: None,
        }
    }

    pub fn contract_rejection(output: impl Into<String>) -> Self {
        Self {
            output: output.into(),
            metadata: ToolCallMetadata {
                // A rejected invocation observed no domain condition. Keep it
                // distinct from an executed observation whose answer is
                // legitimately negative (for example process exit 1).
                outcome_status: Some(ToolOutcomeStatus::Blocked),
                invocation_stage: ToolInvocationStage::RejectedBeforeIo,
                contract_rejected: true,
                // No requested domain effect ran, but the adapter directly
                // observed and completed its deterministic validation. This
                // lets an explicit receipt predicate prove the negative result
                // without relabeling it as a successful mutation.
                semantics: ToolCallSemantics::observation()
                    .with_verification_mode(ToolVerificationMode::ResultContent),
                ..ToolCallMetadata::default()
            },
            finish: None,
        }
    }

    pub fn blocked(output: impl Into<String>) -> Self {
        Self {
            output: output.into(),
            metadata: ToolCallMetadata {
                outcome_status: Some(ToolOutcomeStatus::Blocked),
                ..ToolCallMetadata::default()
            },
            finish: None,
        }
    }

    /// The runtime could not prepare the invocation (no domain I/O ran). The
    /// failure names the exact declaration so the dispatcher can repair its
    /// own projections instead of reporting its mistake to the model.
    pub fn runtime_preparation_failure(
        field: impl Into<String>,
        value: impl Into<String>,
        error: impl std::fmt::Display,
    ) -> Self {
        let field = field.into();
        let value = value.into();
        let error = error.to_string();
        Self {
            output: format!(
                "Error: the runtime could not prepare `{field}` entry `{value}` before running the command: {error}"
            ),
            metadata: ToolCallMetadata {
                outcome_status: Some(ToolOutcomeStatus::Blocked),
                invocation_stage: ToolInvocationStage::RejectedBeforeIo,
                semantics: ToolCallSemantics::observation()
                    .with_verification_mode(ToolVerificationMode::ResultContent),
                runtime_preparation_failure: Some(Box::new(RuntimePreparationFailure {
                    field,
                    value,
                    error,
                })),
                ..ToolCallMetadata::default()
            },
            finish: None,
        }
    }

    pub fn completed_negative_result(output: impl Into<String>) -> Self {
        Self {
            output: output.into(),
            metadata: ToolCallMetadata {
                outcome_status: Some(ToolOutcomeStatus::CompletedWithNegativeResult),
                ..ToolCallMetadata::default()
            },
            finish: None,
        }
    }

    /// End the run on this call (see [`Self::finish`]).
    pub fn with_finish(mut self, finish: aidaemon_core::Finish) -> Self {
        self.finish = Some(finish);
        self
    }

    /// The call moved the rest of the work to the background: the run ends
    /// on it as partial work, and the dispatcher writes the handoff reply
    /// (it knows the user's request and whether completion notifications
    /// reach them).
    pub fn handed_to_background(mut self) -> Self {
        self.metadata.background_handoff = true;
        self.finish = Some(aidaemon_core::Finish::new(
            aidaemon_core::FinishOutcome::Partial,
            None,
        ));
        self
    }

    pub fn with_semantics(mut self, semantics: ToolCallSemantics) -> Self {
        self.metadata.semantics = semantics;
        self
    }

    pub fn with_observation_evidence(
        mut self,
        observations: Vec<ToolObservationEvidence>,
        collection_observations: Vec<ToolCollectionObservation>,
    ) -> Self {
        self.metadata.observations = observations;
        self.metadata.collection_observations = collection_observations;
        self
    }
}

impl ToolCapabilities {
    /// Reads only the daemon's own state or the local machine: no approval, safe to repeat.
    pub const READ_ONLY: Self = Self {
        read_only: true,
        external_side_effect: false,
        needs_approval: false,
        idempotent: true,
        high_impact_write: false,
    };
    /// Changes something outside the daemon in a way that matters: the owner approves it, and it is not safe to repeat.
    pub const EXTERNAL_HIGH_IMPACT: Self = Self {
        read_only: false,
        external_side_effect: true,
        needs_approval: true,
        idempotent: false,
        high_impact_write: true,
    };
    /// Changes only the daemon's own state (a reminder, a note), without approval.
    pub const LOCAL_WRITE: Self = Self {
        read_only: false,
        external_side_effect: false,
        needs_approval: false,
        idempotent: false,
        high_impact_write: false,
    };
    /// Reaches outside the daemon (sends, posts) without approval; not safe to repeat.
    pub const EXTERNAL_WRITE: Self = Self {
        read_only: false,
        external_side_effect: true,
        needs_approval: false,
        idempotent: false,
        high_impact_write: false,
    };
    /// Changes only the daemon's own state, the same way however often it runs.
    pub const IDEMPOTENT_LOCAL_WRITE: Self = Self {
        read_only: false,
        external_side_effect: false,
        needs_approval: false,
        idempotent: true,
        high_impact_write: false,
    };
    /// Reads from outside the daemon (the web, a service): no approval, safe to repeat, its output untrusted.
    pub const READ_ONLY_EXTERNAL: Self = Self {
        read_only: true,
        external_side_effect: true,
        needs_approval: false,
        idempotent: true,
        high_impact_write: false,
    };
    /// Changes the daemon's own configuration or authority: the owner approves it.
    pub const APPROVED_HIGH_IMPACT_LOCAL: Self = Self {
        read_only: false,
        external_side_effect: false,
        needs_approval: true,
        idempotent: false,
        high_impact_write: true,
    };
    /// Reaches outside the daemon without approval, the same way however often it runs.
    pub const IDEMPOTENT_EXTERNAL_WRITE: Self = Self {
        read_only: false,
        external_side_effect: true,
        needs_approval: false,
        idempotent: true,
        high_impact_write: false,
    };
}

impl Default for ToolCapabilities {
    fn default() -> Self {
        Self {
            read_only: false,
            external_side_effect: false,
            needs_approval: true,
            idempotent: false,
            high_impact_write: false,
        }
    }
}

fn string_to_target_hint(key: &str, value: &str) -> Option<ToolTargetHint> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return None;
    }

    let lower_key = key.to_ascii_lowercase();
    if lower_key == "resource_id" {
        return ToolTargetHint::new(ToolTargetHintKind::ResourceId, trimmed);
    }

    if matches!(
        lower_key.as_str(),
        "url" | "verify_url" | "callback_url" | "target_url" | "auth_url"
    ) || trimmed.starts_with("http://")
        || trimmed.starts_with("https://")
    {
        return ToolTargetHint::new(ToolTargetHintKind::Url, trimmed);
    }

    if matches!(
        lower_key.as_str(),
        "path"
            | "file_path"
            | "working_dir"
            | "cwd"
            | "directory"
            | "dir"
            | "repo_path"
            | "repo_dir"
            | "resource_path"
    ) {
        return ToolTargetHint::new(ToolTargetHintKind::Path, trimmed);
    }

    if matches!(
        lower_key.as_str(),
        "project_path" | "project_dir" | "scope" | "project_scope"
    ) {
        return ToolTargetHint::new(ToolTargetHintKind::ProjectScope, trimmed);
    }

    None
}

fn push_unique_target_hint(hints: &mut Vec<ToolTargetHint>, candidate: Option<ToolTargetHint>) {
    let Some(candidate) = candidate else {
        return;
    };
    if !hints.iter().any(|existing| existing == &candidate) {
        hints.push(candidate);
    }
}

fn collect_common_target_hints(arguments: &str) -> Vec<ToolTargetHint> {
    let parsed = match serde_json::from_str::<Value>(arguments) {
        Ok(Value::Object(map)) => map,
        _ => return Vec::new(),
    };

    let mut hints = Vec::new();
    for (key, value) in &parsed {
        match value {
            Value::String(s) => push_unique_target_hint(&mut hints, string_to_target_hint(key, s)),
            Value::Array(items) if matches!(key.as_str(), "paths" | "urls") => {
                for item in items.iter().filter_map(|item| item.as_str()) {
                    push_unique_target_hint(&mut hints, string_to_target_hint(key, item));
                }
            }
            _ => {}
        }
    }
    hints
}

fn default_access_manifest(
    arguments: &str,
    semantics: &ToolCallSemantics,
) -> ToolCallAccessManifest {
    let parsed = serde_json::from_str::<Value>(arguments).ok();
    let execution_cwd = parsed.as_ref().and_then(|value| {
        value
            .get("working_dir")
            .or_else(|| value.get("cwd"))
            .and_then(Value::as_str)
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .map(str::to_string)
    });
    let targets = if semantics.target_hints.is_empty() {
        collect_common_target_hints(arguments)
    } else {
        semantics.target_hints.clone()
    };
    let non_cwd_targets = targets
        .into_iter()
        .filter(|target| {
            matches!(
                target.kind,
                ToolTargetHintKind::Path | ToolTargetHintKind::ProjectScope
            )
        })
        .filter(|target| execution_cwd.as_deref() != Some(target.value.as_str()))
        .collect::<Vec<_>>();
    let mut read_targets = Vec::new();
    if let Some(cwd) = execution_cwd.as_deref()
        && let Some(target) = ToolTargetHint::new(ToolTargetHintKind::ProjectScope, cwd)
    {
        read_targets.push(target);
    }
    if semantics.observes_state() {
        read_targets.extend(non_cwd_targets.iter().cloned());
    }
    let write_targets = if semantics.mutates_state() {
        non_cwd_targets
    } else {
        Vec::new()
    };
    ToolCallAccessManifest {
        execution_cwd,
        read_targets,
        write_targets,
        adapter_read_targets: Vec::new(),
    }
}

/// Classify a mixed-operation tool from the exact `action` enum in its schema.
///
/// This helper intentionally performs no tokenization, substring matching, or
/// interpretation of unknown action names. Tools pass their exhaustive set of
/// read-only enum variants; every missing, malformed, or new variant fails
/// conservatively as a mutation until the tool implementation classifies it.
pub fn semantics_for_exact_read_actions(
    arguments: &str,
    read_actions: &[&str],
    mutation_effects: ToolMutationEffects,
) -> ToolCallSemantics {
    let action = serde_json::from_str::<Value>(arguments)
        .ok()
        .and_then(|value| {
            value
                .get("action")
                .and_then(Value::as_str)
                .map(str::to_string)
        });
    let mut semantics = if action
        .as_deref()
        .is_some_and(|action| read_actions.contains(&action))
    {
        ToolCallSemantics::observation().with_verification_mode(ToolVerificationMode::ResultContent)
    } else if mutation_effects.is_empty() {
        ToolCallSemantics::mutation()
    } else {
        ToolCallSemantics::mutation_with(mutation_effects)
    };
    for target_hint in collect_common_target_hints(arguments) {
        semantics = semantics.with_target_hint(target_hint.kind, target_hint.value);
    }
    semantics
}

fn default_semantics_from_identity(arguments: &str, caps: ToolCapabilities) -> ToolCallSemantics {
    let mut semantics = if caps.read_only {
        ToolCallSemantics::observation().with_verification_mode(ToolVerificationMode::ResultContent)
    } else {
        // Unknown non-read-only tools fail conservatively as mutations. Mixed
        // tools must override `call_semantics` with an exact match on their
        // schema enum; names, descriptions, and arbitrary action vocabulary are
        // never an authority source.
        ToolCallSemantics::mutation()
    };

    for target_hint in collect_common_target_hints(arguments) {
        semantics = semantics.with_target_hint(target_hint.kind, target_hint.value);
    }
    semantics
}

/// The scope of an approval the agent kernel gave a call (see
/// [`ToolCallContext::kernel_approved`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApprovalScope {
    /// This call came through the kernel, which judged it.
    Call,
    /// One exact inner request (`METHOD url`) of an outer call the kernel
    /// approved, for example `manage_api`'s live probe.
    Request { method: String, url: String },
}

/// Refuse `what` (the tool and action, as the refusal names them) unless the
/// agent kernel approved the whole call ([`ApprovalScope::Call`]). An
/// approval scoped to one inner request never authorizes the outer call.
pub fn require_call_approval(scope: Option<&ApprovalScope>, what: &str) -> anyhow::Result<()> {
    if scope != Some(&ApprovalScope::Call) {
        anyhow::bail!(
            "{what} requires approval through the agent kernel; it was called outside an \
             approved agent call"
        );
    }
    Ok(())
}

/// One call as the kernel's approval rules show it to
/// [`ToolSemantics::owner_approval_request`].
#[derive(Debug, Clone, Copy)]
pub struct ApprovalCall<'a> {
    /// The arguments the dispatcher will execute (for a tool whose calls the
    /// kernel judges in canonical form, the canonical form; otherwise the
    /// model's own).
    pub arguments: &'a Value,
    /// The arguments as the model sent them, for a card about a call whose
    /// arguments cannot be read.
    pub as_sent: &'a Value,
    /// The dispatcher refuses this call before it runs (an out-of-scope
    /// target nobody may authorize), so nothing about it needs the owner.
    pub refused: bool,
}

impl<'a> ApprovalCall<'a> {
    /// A call the dispatcher runs as the model sent it.
    pub fn as_sent(arguments: &'a Value) -> Self {
        Self {
            arguments,
            as_sent: arguments,
            refused: false,
        }
    }
}

/// What a tool says about the owner's approval for one call.
#[derive(Debug, Clone, PartialEq)]
pub enum OwnerApprovalNeed {
    /// The tool has no opinion: the approval policy's allow rules and mode
    /// decide.
    Unjudged,
    /// The tool judged the call and it needs no approval.
    NotNeeded,
    /// Ask the owner with this request (unless a grant covers it).
    Ask(aidaemon_core::OwnerApprovalRequest),
}

/// The dispatcher's facts about one tool call, passed to the tool beside its
/// arguments.
///
/// This is a Rust-side control-plane type: it is NEVER serialized and never
/// appears in model-visible JSON, tool schemas, logs, or persisted tool
/// arguments. Every fact about who is calling, from where, and under what
/// authority lives here and only here: a tool's arguments are the model's
/// own, and the dispatcher strips any `_`-prefixed key a model sends.
#[derive(Clone, Default)]
pub struct ToolCallContext {
    /// True only after the final common dispatcher revalidated an exact,
    /// action-bound `MandateAuthorityGrant` for this mutating call, so tools
    /// can honor owner-delegated autonomy.
    pub mandate_preapproved: bool,
    /// True only when the common dispatcher resolved this call to an active
    /// autonomous mandate. Network adapters use this control-plane bit to keep
    /// one target-bound call from following redirects outside the target that
    /// was evaluated by the mandate authority kernel.
    pub mandate_execution: bool,
    /// Hard negative task contract propagated from the validated request.
    /// Open-ended adapters must prove an operation is observational before I/O.
    pub mutation_forbidden: bool,
    /// What the agent kernel approved, set only by the dispatcher (never
    /// from arguments): `Call` for a call that came through the kernel,
    /// whose `ApprovalPolicy` already asked the owner where the daemon's
    /// rules require it; `Request` for one exact inner request an approved
    /// outer call makes. A tool that needs the owner's approval refuses a
    /// call without a matching scope rather than asking itself.
    pub kernel_approved: Option<ApprovalScope>,
    /// The turn is a trusted scheduled session (never one under a mandate),
    /// set only by the dispatcher from the channel context and the goal's
    /// provenance.
    pub trusted_session: bool,
    /// The role of the turn's user (`None` outside the dispatcher: an
    /// unknown caller is not the owner).
    pub user_role: Option<UserRole>,
    /// The session was started by an automated trigger (an email, an
    /// event), not by the owner.
    pub untrusted_source: bool,
    /// Exact out-of-scope targets the controller routed to the owner's
    /// approval instead of refusing them.
    pub scope_escalation: Option<ScopeEscalation>,
    /// The session the call belongs to (empty outside the dispatcher).
    pub session_id: String,
    /// The session whose owner approvals cover this call: the chat that
    /// started the work. A sub-agent runs in a session of its own but works
    /// for that chat, so a tool's own session-scoped grants ("allow for
    /// session") key on this, never on `session_id`. Empty: `session_id`.
    pub grant_session: String,
    /// Visibility of the channel the turn came from (`None` outside the
    /// dispatcher; each tool keeps its own fallback).
    pub channel_visibility: Option<ChannelVisibility>,
    /// The channel the turn came from, when the channel has an id.
    pub channel_id: Option<String>,
    /// The task the call runs under.
    pub task_id: Option<String>,
    /// The owner/user message text of this turn (control-plane only; used for
    /// synchronous provenance verification in `remember_fact`).
    pub user_message: Option<String>,
    /// The model's id for this tool call.
    pub tool_call_id: Option<String>,
    /// The call is the only one in a root turn's model response, so a reply
    /// the tool finishes the run with answers the user's request directly.
    pub lone_root_call: bool,
    /// The session's current turn.
    pub turn_id: Option<String>,
    /// The goal the call serves: the agent's goal, or (for `cli_agent` and
    /// `terminal`) the goal of the executor's task, so background
    /// notifications reach the origin session.
    pub goal_id: Option<String>,
    /// The goal run of the mandate fence the call runs under.
    pub goal_run_id: Option<String>,
    /// The task attempt of the mandate fence the call runs under.
    pub task_attempt_id: Option<String>,
    /// The mandate of the fence the call runs under.
    pub mandate_id: Option<String>,
    /// The mandate version of the fence the call runs under.
    pub mandate_version: Option<i64>,
    /// The single project the turn is scoped to.
    pub project_scope: Option<String>,
    /// The project the owner's turn works in (an app project, a chat placed
    /// in one), set only by the dispatcher from typed turn state. `None` for
    /// guests, public channels and mandate runs: project-scoped writes (a
    /// memory tool's project notes) key on it.
    pub project: Option<aidaemon_core::ProjectRef>,
    /// A guest's granted workspace root (only under an active grant).
    pub workspace_collaboration_root: Option<String>,
    /// The turn's trusted file roots (set for `terminal`), so a run moved to
    /// the background records the trust its launch was judged with.
    pub trust_roots: Option<Vec<String>>,
    /// The cwd relative paths resolve against for [`Self::trust_roots`].
    pub trust_cwd: Option<String>,
    /// The live model (set for `computer_use`).
    pub model: Option<String>,
    /// The provider kind behind [`Self::model`], as the daemon names it.
    pub provider_kind: Option<String>,
    /// The router's models in order, when a router is configured.
    pub model_chain: Option<Vec<String>>,
    /// Application facts whose types cannot live in the SDK (they depend on
    /// the application's configuration), read by the tool that needs them
    /// through a typed getter.
    pub extensions: aidaemon_core::Extensions,
}

impl std::fmt::Debug for ToolCallContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ToolCallContext")
            .field("mandate_preapproved", &self.mandate_preapproved)
            .field("mandate_execution", &self.mandate_execution)
            .field("mutation_forbidden", &self.mutation_forbidden)
            .field("kernel_approved", &self.kernel_approved)
            .field("trusted_session", &self.trusted_session)
            .field("user_role", &self.user_role)
            .field("untrusted_source", &self.untrusted_source)
            .field("scope_escalation", &self.scope_escalation)
            .field("session_id", &self.session_id)
            .field("channel_visibility", &self.channel_visibility)
            .field("channel_id", &self.channel_id)
            .field("task_id", &self.task_id)
            .field(
                "user_message",
                &self.user_message.as_ref().map(|_| "[USER MESSAGE]"),
            )
            .field("tool_call_id", &self.tool_call_id)
            .field("lone_root_call", &self.lone_root_call)
            .field("turn_id", &self.turn_id)
            .field("goal_id", &self.goal_id)
            .field("goal_run_id", &self.goal_run_id)
            .field("task_attempt_id", &self.task_attempt_id)
            .field("mandate_id", &self.mandate_id)
            .field("mandate_version", &self.mandate_version)
            .field("project_scope", &self.project_scope)
            .field(
                "workspace_collaboration_root",
                &self
                    .workspace_collaboration_root
                    .as_ref()
                    .map(|_| "[SCOPED WORKSPACE]"),
            )
            .field("trust_roots", &self.trust_roots)
            .field("trust_cwd", &self.trust_cwd)
            .field("model", &self.model)
            .field("provider_kind", &self.provider_kind)
            .field("model_chain", &self.model_chain)
            .field("extensions", &self.extensions)
            .finish()
    }
}

impl ToolCallContext {
    /// The session id, or `None` when the call carries none.
    pub fn session(&self) -> Option<&str> {
        Some(self.session_id.as_str()).filter(|id| !id.trim().is_empty())
    }

    /// The session a tool's own session-scoped grants key on
    /// ([`Self::grant_session`], else the call's session).
    pub fn grants_session(&self) -> &str {
        if self.grant_session.trim().is_empty() {
            &self.session_id
        } else {
            &self.grant_session
        }
    }
}

/// Filesystem targets a tool call declared that fall outside the compiled
/// task scope but are not protected host data or credential stores. The
/// controller does not reject such a call outright; it hands the exact
/// out-of-scope targets to the tool, which must obtain explicit user approval
/// (or a persisted capability grant) before running with them.
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScopeEscalation {
    #[serde(default)]
    pub read_paths: Vec<String>,
    #[serde(default)]
    pub write_paths: Vec<String>,
}

impl ScopeEscalation {
    pub fn is_empty(&self) -> bool {
        self.read_paths.is_empty() && self.write_paths.is_empty()
    }
}

/// A tool-owned decision about whether a previously successful durable receipt
/// still represents current state.
///
/// Most mutations cannot be repeated safely and therefore use `Replay`. Tools
/// with an exact deterministic postcondition may opt into current-state
/// reconciliation and either re-execute when that postcondition is missing or
/// block when the target drifted in a way that could make repetition unsafe.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DurableReplayDecision {
    Replay,
    Reexecute { reason: String },
    Block { reason: String },
}

/// Tool trait — system tools, terminal, MCP-proxied tools.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolArgumentContractViolation {
    pub reason: String,
    pub recovery_hint: Option<String>,
}

impl ToolArgumentContractViolation {
    pub fn new(reason: impl Into<String>) -> Self {
        Self {
            reason: reason.into(),
            recovery_hint: None,
        }
    }

    pub fn with_recovery_hint(mut self, hint: impl Into<String>) -> Self {
        self.recovery_hint = Some(hint.into());
        self
    }
}

/// Permission persistence mode for commands requiring owner approval.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PermissionMode {
    /// Safe/Medium/High persist; Critical remains session-scoped.
    #[default]
    Default,
    /// All approvals remain session-scoped.
    Cautious,
    /// All approvals persist, including Critical.
    Yolo,
}

impl std::fmt::Display for PermissionMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PermissionMode::Default => write!(f, "default"),
            PermissionMode::Cautious => write!(f, "cautious"),
            PermissionMode::Yolo => write!(f, "yolo"),
        }
    }
}

/// Distinguishes different kinds of approval requests so channels can render
/// appropriate buttons (e.g., Allow Once / Deny for commands vs Confirm / Cancel
/// for scheduled-goal confirmations).
#[derive(Debug, Clone, Copy, Default)]
pub enum ApprovalKind {
    /// Standard command approval (Allow Once / Allow Session / Allow Always / Deny).
    #[default]
    Command,
    /// Point-of-action approval that can authorize only this invocation.
    /// Channels must not offer session or persistent approval buttons.
    CommandOnce,
    /// Scheduled-goal confirmation (Confirm / Cancel).
    GoalConfirmation,
    /// Exact owner confirmation for a persisted Autopilot mandate policy.
    /// Kept distinct so channels never infer high-autonomy presentation from
    /// user or model prose.
    AutopilotConfirmation,
    /// The agent asks the owner to do something themselves on a live surface
    /// (sign in, enter a code): Done or Not now, this one time only.
    Handoff,
}

/// Response to an approval request from the user.
#[derive(Debug, Clone)]
pub enum ApprovalResponse {
    /// Allow this specific command only
    AllowOnce,
    /// Allow this command prefix for the current session (resets on restart)
    AllowSession,
    /// Allow this command prefix forever (persists to database)
    AllowAlways,
    /// Deny the command
    Deny,
}

/// Relative impact of an operation requiring approval.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RiskLevel {
    Safe,
    Medium,
    High,
    Critical,
}

impl std::fmt::Display for RiskLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RiskLevel::Safe => write!(f, "Safe"),
            RiskLevel::Medium => write!(f, "Medium"),
            RiskLevel::High => write!(f, "High"),
            RiskLevel::Critical => write!(f, "Critical"),
        }
    }
}

impl RiskLevel {
    /// Whether this risk level represents an action that should interrupt the
    /// owner for approval. Safe and medium operations may still be observable
    /// or locally mutating, but they are not dangerous enough to justify
    /// blocking an otherwise authorized task.
    pub const fn requires_owner_approval(self) -> bool {
        matches!(self, Self::High | Self::Critical)
    }
}

/// Typed presentation requested for an exact goal/mandate confirmation.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum GoalConfirmationStyle {
    #[default]
    Standard,
    Autopilot,
}

/// Role assigned to an agent for role-based tool scoping.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentRole {
    /// Root agent — routes, classifies, full tool access (legacy behavior).
    Orchestrator,
    /// Plans & delegates — management tools only.
    TaskLead,
    /// Executes a single task — action tools + report_blocker.
    Executor,
}

/// How one call changes a file (see [`ToolSemantics::call_file_write`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileWriteKind {
    /// Replaces this exact text.
    Edit { old_text: String, replace_all: bool },
    /// Replaces each exact text in order, each in the result of the one
    /// before: all of them, or nothing.
    Edits(Vec<TextEdit>),
    /// Replaces the whole file.
    Replace,
    /// Adds to the end of the file.
    Append,
}

/// One find-and-replace of a [`FileWriteKind::Edits`] batch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextEdit {
    pub old_text: String,
    pub replace_all: bool,
}

/// The file one call writes, as the tool's arguments name it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileWrite {
    pub path: String,
    pub kind: FileWriteKind,
}

/// A write in progress under a [`FileFence`]. Dropping it records nothing.
#[async_trait]
pub trait FileWriteGuard: Send {
    /// The write landed.
    async fn committed(self: Box<Self>);
}

/// Handed to a file tool by a host whose agents share a workspace. Without
/// one the tool behaves as it would alone.
#[async_trait]
pub trait FileFence: Send + Sync {
    /// The call read these exact bytes of `path`.
    async fn observed(&self, path: &str, bytes: &[u8]);

    /// Hold `path` for this write, or say why the write must not happen.
    /// Taken before the tool reads the file it is about to change, and held
    /// until the write has landed.
    async fn begin_write(&self, path: &str) -> Result<Box<dyn FileWriteGuard>, String>;

    /// Claim the delivery to the owner of the artifact `subject` names (a
    /// page's screenshot names the page) for this call. One request's agents
    /// deliver each artifact once: whoever delivers it first owns it, and a
    /// later claim gets who did and when. Release a claim whose delivery
    /// then failed ([`Self::release_delivery`]).
    async fn claim_delivery(&self, _subject: &str) -> Result<(), DeliveredArtifact> {
        Ok(())
    }

    /// Give back a claim whose delivery did not happen.
    async fn release_delivery(&self, _subject: &str) {}

    /// The call declares `deliverable` for the owner. A helper's run keeps
    /// it on its record and sends it once, when the run ends: the last one
    /// of each kind it declared, so a capture taken before the work was
    /// done is replaced by the final one, never sent beside it. Anyone
    /// else's (the turn's own agent, a host with no run record) is sent now
    /// by the caller, under [`Self::claim_delivery`].
    async fn declare_deliverable(&self, deliverable: Deliverable) -> DeliveryPlan {
        DeliveryPlan::Now(deliverable)
    }
}

/// What a deliverable is, by kind: each run delivers one of each kind (the
/// last it declared), and each request delivers each subject once.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum DeliverableKind {
    /// A page's screenshot, named by its page ("demo.ddev.site").
    Screenshot { page: String },
    /// Any other file, named by its file name.
    File { name: String },
}

impl DeliverableKind {
    /// The delivery ledger's key for it.
    pub fn subject(&self) -> String {
        match self {
            Self::Screenshot { page } => format!("screenshot:{page}"),
            Self::File { name } => format!("file:{name}"),
        }
    }

    /// The kind in the owner's words ("a screenshot of demo.ddev.site").
    pub fn words(&self) -> String {
        match self {
            Self::Screenshot { page } => format!("a screenshot of {page}"),
            Self::File { name } => format!("the file {name}"),
        }
    }
}

/// The send a tool hands over with a deliverable sent later: run once, it
/// reports whether the channel accepted it.
pub type DeliverySend = Box<
    dyn FnOnce() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + Send>>
        + Send
        + Sync,
>;

/// One artifact a call declares for the owner.
pub struct Deliverable {
    pub kind: DeliverableKind,
    /// What the owner reads with it ("Screenshot of demo.ddev.site").
    pub caption: String,
    pub send: DeliverySend,
}

impl std::fmt::Debug for Deliverable {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Deliverable")
            .field("kind", &self.kind)
            .field("caption", &self.caption)
            .finish_non_exhaustive()
    }
}

/// When a declared deliverable is sent ([`FileFence::declare_deliverable`]).
#[derive(Debug)]
pub enum DeliveryPlan {
    /// The caller sends it now, under a delivery claim.
    Now(Deliverable),
    /// It is on the run's record and is sent when the run ends. `replaced`:
    /// it took the place of an earlier one of the same kind.
    AtRunEnd { replaced: bool },
}

/// An artifact one of the request's agents already delivered to the owner.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeliveredArtifact {
    /// Who delivered it, in words the owner reads ("you", or the helper's
    /// mission).
    pub by: String,
    pub at: chrono::DateTime<chrono::Utc>,
}

impl DeliveredArtifact {
    /// When it was delivered, on the owner's clock ("3:41:22 AM").
    pub fn owner_time(&self) -> String {
        self.at
            .with_timezone(&chrono::Local)
            .format("%-I:%M:%S %p")
            .to_string()
    }
}

/// This call's [`FileFence`], carried in [`ToolCallContext::extensions`].
#[derive(Clone)]
pub struct CallFileFence(pub std::sync::Arc<dyn FileFence>);

/// The call's file fence, if its host gave it one.
pub fn file_fence(facts: &ToolCallContext) -> Option<&std::sync::Arc<dyn FileFence>> {
    facts
        .extensions
        .get::<CallFileFence>()
        .map(|fence| &fence.0)
}

/// A job a tool runs in the background for a chat.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BackgroundJob {
    /// The tool's own handle for it; never shown.
    pub key: String,
    /// What it is, in plain words.
    pub title: String,
    pub started_at: chrono::DateTime<chrono::Utc>,
    /// The task (turn) that started it, when known.
    pub task_id: Option<String>,
    /// The run it is in the runtime's records, when it is one.
    pub run: Option<String>,
}

/// What a tool says about a call without executing it: its capabilities,
/// typed semantics, access manifest, receipt protocol, effects and trust.
/// Every method has a conservative default; a tool overrides only what it
/// can state exactly.
#[async_trait]
pub trait ToolSemantics: Send + Sync {
    /// Canonicalize provider argument projections before any semantics,
    /// authority, retry, or access decision is made. The default is identity;
    /// adapters with representational aliases or optional-empty projection
    /// quirks can normalize them without teaching the orchestration layer
    /// adapter-specific rules.
    fn canonicalize_arguments(
        &self,
        arguments: &str,
    ) -> Result<String, ToolArgumentContractViolation> {
        Ok(arguments.to_string())
    }

    /// Adapter-owned, deterministic argument invariants evaluated by the
    /// common dispatcher before any tool I/O. The default accepts all schema-
    /// valid calls. Rejections become typed `contract_rejected` receipts.
    fn validate_arguments(&self, _arguments: &str) -> Result<(), ToolArgumentContractViolation> {
        Ok(())
    }

    /// Task lifecycle callback fired after the agent emits `TaskEnd`.
    /// Tools that spawn background activity can use this to clean up
    /// task-scoped resources.
    async fn on_task_end(&self, _task_id: &str, _session_id: &str) -> anyhow::Result<()> {
        Ok(())
    }

    /// Live state this tool holds for a session that outlives a turn (for
    /// example background processes still running), rendered for the next
    /// turn's task context so a follow-up sees it instead of guessing.
    async fn session_context_note(&self, _session_id: &str) -> Option<String> {
        None
    }

    /// The jobs this tool is running in the background for `session_id`
    /// (they outlive the turn that started them), as the chat's list of
    /// running work shows them.
    async fn background_jobs(&self, _session_id: &str) -> Vec<BackgroundJob> {
        Vec::new()
    }

    /// Stop the background job `key` (from [`Self::background_jobs`]) and
    /// read its state back: `true` only once the job is gone.
    async fn stop_background_job(&self, _key: &str) -> bool {
        false
    }

    /// How many jobs task `task_id` started that are still running and that
    /// the task's end would stop: nothing reports their result, so a run that
    /// ended now would lose their work.
    async fn jobs_ended_by_task_end(&self, _task_id: &str) -> usize {
        0
    }

    /// Categorize this tool for role-based scoping.
    /// Default: Action (most tools are action tools).
    fn tool_role(&self) -> ToolRole {
        ToolRole::Action
    }

    /// How the dispatcher and the engine treat this tool. Default: nothing
    /// special.
    fn dispatch_facts(&self) -> ToolDispatchFacts {
        ToolDispatchFacts::default()
    }

    /// Capability metadata used by the execution policy and risk gate.
    /// Defaults are intentionally conservative.
    fn capabilities(&self) -> ToolCapabilities {
        ToolCapabilities::default()
    }

    /// The tool only manages the owner's own durable policy (mandates). A
    /// request assessment that narrows a turn's tools still offers it to the
    /// owner in a private chat, but only calls `owner_control_plane_call`
    /// accepts are admitted there.
    fn owner_control_plane(&self) -> bool {
        false
    }

    /// Whether this exact call is safe on a turn whose assessment did not
    /// name the tool: read-only, or committing only through an explicit
    /// owner confirmation. Decided from the tool's own schema enum.
    fn owner_control_plane_call(&self, _arguments: &str) -> bool {
        false
    }

    /// The owner approval this exact call needs before it runs, judged from
    /// the call and the dispatcher's facts for it (never from `_` arguments).
    /// The kernel's approval rules ask it for every call and send the card
    /// it returns. The default has no opinion, so the approval policy's mode
    /// decides.
    async fn owner_approval_request(
        &self,
        _call: &ApprovalCall<'_>,
        _facts: &ToolCallContext,
    ) -> OwnerApprovalNeed {
        OwnerApprovalNeed::Unjudged
    }

    /// Machine-receipt protocol emitted by this adapter.
    ///
    /// Keep this independent from natural-language descriptions and call
    /// semantics: it exists solely to type-check completion predicates.
    fn receipt_kind(&self, _arguments: &str) -> ToolReceiptKind {
        ToolReceiptKind::Generic
    }

    /// Structured completion semantics for a specific call.
    ///
    /// Default behavior derives a conservative fallback from `capabilities()`.
    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
        default_semantics_from_identity(arguments, self.capabilities())
    }

    /// Filesystem access roles for this exact call. Open-ended adapters should
    /// override this when their schema exposes explicit read/write grants.
    fn call_access_manifest(&self, arguments: &str) -> ToolCallAccessManifest {
        let semantics = self.call_semantics(arguments);
        default_access_manifest(arguments, &semantics)
    }

    /// The paths this call reads and writes, as `ProtectedPathGuard` judges
    /// them. Defaults to the access manifest; a tool overrides it for a path
    /// that scope checks must not see as a task read.
    fn guarded_paths(&self, arguments: &str) -> (Vec<String>, Vec<String>) {
        let manifest = self.call_access_manifest(arguments);
        let values =
            |targets: Vec<ToolTargetHint>| targets.into_iter().map(|target| target.value).collect();
        (
            values(manifest.read_targets),
            values(manifest.write_targets),
        )
    }

    /// Capabilities supplied by the adapter rather than requested as task
    /// data.  The common dispatcher uses this typed lane when attenuating the
    /// call against the task manifest.  The default is empty so an adapter
    /// cannot accidentally widen authority by inheriting a generic grant.
    fn adapter_owned_access_manifest(&self, _arguments: &str) -> ToolCallAccessManifest {
        ToolCallAccessManifest::default()
    }

    /// Reconcile a successful durable receipt with current state before replay.
    ///
    /// The conservative default always replays. An override may return
    /// `Reexecute` only when repeating the exact same invocation is safe after
    /// the observed state transition, and `Block` when current state cannot be
    /// reconciled safely.
    async fn durable_replay_decision(&self, _arguments: &str) -> DurableReplayDecision {
        DurableReplayDecision::Replay
    }

    /// Exact receipt subjects this adapter reports verbatim: fixed collection
    /// IDs and the namespaces of member identities it mints. The checklist
    /// tool publishes the union so declared targets bind only to identities a
    /// receipt can carry. The default advertises nothing.
    fn stable_observation_subjects(&self) -> Vec<StableObservationSubject> {
        Vec::new()
    }

    /// The file this exact call writes and how, read from its arguments. A
    /// tool that does not declare one is invisible to stale-write checks.
    fn call_file_write(&self, _arguments: &str) -> Option<FileWrite> {
        None
    }

    /// What the file would hold after this exact call, were it holding
    /// `current` now (`None`: no such file). `Err` is the tool's own reason
    /// the call cannot apply to that content. A tool that cannot say returns
    /// `None`, and a host that asks then treats the call as changing all of
    /// the file.
    fn file_write_result(
        &self,
        _arguments: &str,
        _current: Option<&[u8]>,
    ) -> Option<Result<Vec<u8>, String>> {
        None
    }

    /// What this call carries out of the machine if it only reads.
    fn call_outbound(&self, _arguments: &str) -> aidaemon_core::Outbound {
        aidaemon_core::Outbound::Nothing
    }

    /// The typed effects of this exact call (effect class and normalized
    /// target), which the kernel checks against the owner's declines and
    /// hands the approval and egress policies. Build keys only with the
    /// kernel constructors, through `command_effects::{path_effect,
    /// egress_effect, url_effect}`. The default is `CallEffects::none()` for a
    /// tool whose capabilities are read-only and `CallEffects::unknown()`
    /// otherwise; a tool that can name what a call does overrides it.
    fn call_effects(&self, _arguments: &str) -> aidaemon_core::CallEffects {
        if self.capabilities().read_only {
            aidaemon_core::CallEffects::none()
        } else {
            aidaemon_core::CallEffects::unknown()
        }
    }

    /// Every file or resource this exact call names as something it reads
    /// or writes, from typed facts only (never its prose): its declared
    /// target hints, its access manifest and its typed path effects. A tool
    /// whose arguments name more structurally (a shell command's operands)
    /// adds them. One reading for every tool, so a fact about a file (the
    /// request's own work produced it) reaches each call that names it.
    fn named_files(&self, arguments: &str) -> Vec<String> {
        declared_named_files(self, arguments)
    }

    /// Authority annotations for this exact call, judged against the turn's
    /// trusted roots: read-only, destructive, idempotent, and whether it
    /// sends data or acts outside the owner's machine and workspace
    /// (`egress`). Derived from the call's typed semantics, never from the
    /// tool's name. Roots matter for effects whose class depends on where
    /// they land (a delete inside the owner's roots is not egress); empty
    /// roots mean every such target counts as outside them. The default
    /// ignores the roots.
    fn call_annotations_in(
        &self,
        arguments: &str,
        _roots: &TrustRoots<'_>,
    ) -> aidaemon_core::ToolAnnotations {
        default_call_annotations(self.capabilities(), &self.call_semantics(arguments))
    }

    /// Who authored what this exact call returns. The default is
    /// `Untrusted` iff the tool reaches outside the machine
    /// (`external_side_effect`); local tools override with the owner's
    /// trusted roots.
    fn output_trust(
        &self,
        _arguments: &str,
        _roots: &TrustRoots<'_>,
    ) -> aidaemon_core::SourceTrust {
        if self.capabilities().external_side_effect {
            aidaemon_core::SourceTrust::Untrusted
        } else {
            aidaemon_core::SourceTrust::Trusted
        }
    }

    /// A few plain words the call itself gave for what it does ("running
    /// the site installer"), for the owner's status line and lists of
    /// running work. Never authority. Default: none.
    fn call_title(&self, _arguments: &str) -> Option<String> {
        None
    }

    /// Whether this tool is currently operational.
    ///
    /// Default: true. Override for tools with dynamic backends that may be
    /// temporarily unavailable at runtime.
    fn is_available(&self) -> bool {
        true
    }

    /// Whether the tool is offered on a turn of `session_id`, judged from
    /// the tool's own typed state, never from the request's wording.
    ///
    /// Default: true. A tool whose only effect lands on one client
    /// connection (the agent-driven view) is offered only while that
    /// session's turn came from a connection that can show it.
    fn offered_in_session(&self, _session_id: &str) -> bool {
        true
    }
}

/// Effects that send data or act outside the owner's machine and workspace,
/// or cannot be undone. A call with any of these is egress.
pub const EGRESS_EFFECTS: ToolMutationEffects = ToolMutationEffects::EXTERNAL_DELIVERY
    .union(ToolMutationEffects::REMOTE_MUTATION)
    .union(ToolMutationEffects::REMOTE_DEPLOY)
    .union(ToolMutationEffects::DESTRUCTIVE)
    .union(ToolMutationEffects::CONFIGURATION);

/// Per-call authority annotations from a tool's capabilities and the call's
/// typed semantics.
pub fn default_call_annotations(
    cap: ToolCapabilities,
    semantics: &ToolCallSemantics,
) -> aidaemon_core::ToolAnnotations {
    let read_only = cap.read_only
        || (matches!(
            semantics.effect,
            ToolCallEffect::Observation | ToolCallEffect::Administrative
        ) && !semantics.mutates_state());
    let effects = semantics.mutation_effects;
    let egress = !read_only
        && (effects.intersects(EGRESS_EFFECTS)
            || (cap.external_side_effect && !effects.has_specific_effects()));
    aidaemon_core::ToolAnnotations {
        read_only,
        destructive: !read_only && effects.intersects(ToolMutationEffects::DESTRUCTIVE),
        idempotent: read_only,
        egress,
    }
}

/// The folders a request's work made fresh for itself (a spawn's
/// `new_folders`, claimed empty by the runtime), shared by every run of the
/// request's tree. Everything inside them is the work's own: a change or a
/// delete there acts on nothing anyone else made. A planning and effect
/// fact only, never a trust source for what is read there (a package
/// manager fills them with other people's code).
#[derive(Debug, Clone, Default)]
pub struct OwnedFolders(std::sync::Arc<std::sync::RwLock<Vec<String>>>);

impl OwnedFolders {
    /// Record folders the runtime just made for this request's work.
    pub fn claim(&self, folders: &[String]) {
        let mut owned = self.0.write().unwrap_or_else(|e| e.into_inner());
        for folder in folders {
            let folder = folder.trim();
            if std::path::Path::new(folder).is_absolute() && !owned.iter().any(|f| f == folder) {
                owned.push(folder.to_string());
            }
        }
    }

    /// Give back folders that were removed again (the work never started).
    pub fn release<P: AsRef<std::path::Path>>(&self, folders: &[P]) {
        let mut owned = self.0.write().unwrap_or_else(|e| e.into_inner());
        owned.retain(|kept| {
            !folders
                .iter()
                .any(|folder| std::path::Path::new(kept) == folder.as_ref())
        });
    }

    /// The folders, as claimed.
    pub fn list(&self) -> Vec<String> {
        self.0.read().unwrap_or_else(|e| e.into_inner()).clone()
    }

    /// Where a call's declared writes land that does not exist yet, taken
    /// just before it runs: what it may create. Once it succeeded,
    /// [`Self::claim_created`] claims each that it did create as a folder.
    pub fn absent_write_targets(effects: &aidaemon_core::CallEffects) -> Vec<std::path::PathBuf> {
        effects
            .keys
            .iter()
            .filter(|key| key.class == aidaemon_core::EffectClass::Write)
            .map(|key| std::path::PathBuf::from(shellexpand::tilde(key.target.trim()).as_ref()))
            .filter(|path| path.is_absolute() && std::fs::symlink_metadata(path).is_err())
            .collect()
    }

    /// Ownership from evidence of creation: of `absent` (taken before a
    /// call that then succeeded), each path that is now a folder was made
    /// by this request's work (`mkdir`, a project tool's init in a new
    /// path), so it joins the request's owned folders, as a spawn's
    /// declared `new_folders` do (live 2026-11-13: two helpers each created
    /// their site's folder without declaring it, and every later change
    /// there was judged as someone else's project). A folder that existed
    /// before never joins. Returns what it claimed.
    pub fn claim_created(&self, absent: &[std::path::PathBuf]) -> Vec<String> {
        let created: Vec<String> = absent
            .iter()
            .filter(|path| {
                std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_dir())
            })
            .map(|path| path.display().to_string())
            .collect();
        self.claim(&created);
        created
    }
}

#[cfg(test)]
mod owned_folder_tests {
    use super::OwnedFolders;

    /// A folder a succeeded call created joins the request's own; one that
    /// existed before it does not, and neither does a file it wrote.
    #[test]
    fn a_folder_a_call_created_becomes_owned() {
        let base = tempfile::tempdir().unwrap();
        let fresh = base.path().join("claude-drupal-11");
        let file = base.path().join("notes.txt");
        let before = base.path().join("existing-site");
        std::fs::create_dir(&before).unwrap();
        let key = |path: &std::path::Path| aidaemon_core::EffectKey {
            class: aidaemon_core::EffectClass::Write,
            target: path.display().to_string(),
        };
        let effects = aidaemon_core::CallEffects {
            keys: vec![key(&fresh), key(&file), key(&before)],
            complete: false,
            understood: true,
        };
        let absent = OwnedFolders::absent_write_targets(&effects);
        assert_eq!(absent, vec![fresh.clone(), file.clone()]);
        std::fs::create_dir(&fresh).unwrap();
        std::fs::write(&file, "x").unwrap();
        let owned = OwnedFolders::default();
        assert_eq!(
            owned.claim_created(&absent),
            vec![fresh.display().to_string()]
        );
        assert_eq!(owned.list(), vec![fresh.display().to_string()]);
    }
}

/// Whether absolute `path` resolves inside one of `folders`, by the one
/// path resolver every scope check uses (`aidaemon_policies::resolves_within`).
pub fn within_owned(path: &str, folders: &[String]) -> bool {
    let expanded = shellexpand::tilde(path.trim()).into_owned();
    let path = std::path::Path::new(&expanded);
    path.is_absolute()
        && folders.iter().any(|folder| {
            aidaemon_policies::resolves_within(path, std::path::Path::new(folder.trim()))
        })
}

/// How one of a request's files came to be, when the request's own work
/// produced it ([`ProducedFiles`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProducedFile {
    /// A capture one of the request's calls saved, showing `kind` (a
    /// browser screenshot shows its page).
    Capture(DeliverableKind),
    /// A file one of the request's calls created where nothing was before.
    Created,
}

impl ProducedFile {
    /// What it is, in plain words for the untrusted-call check.
    pub fn words(&self) -> String {
        match self {
            Self::Capture(kind) => format!("this request's own capture: {}", kind.words()),
            Self::Created => "a file this request's own work created".to_string(),
        }
    }
}

/// The files a request's own work produced, shared by every run of its
/// tree, from evidence rather than anyone's account of them: a capture a
/// tool noted as it saved it, and a file a succeeded call created where
/// its declared write found nothing before ([`Self::claim_created`], the
/// file counterpart of [`OwnedFolders::claim_created`]). Each is the
/// request's own artifact wherever it is saved (a capture lands in the
/// daemon's inbox, outside any project). Keyed by the resolved path, and a
/// capture also by its resource id, so either handle a later call names
/// finds it. A planning and effect fact, never a trust source for what the
/// file holds.
#[derive(Debug, Clone, Default)]
pub struct ProducedFiles(
    std::sync::Arc<std::sync::RwLock<std::collections::HashMap<String, ProducedFile>>>,
);

impl ProducedFiles {
    /// A capture was saved at `path` (with `resource_id`, when it has one)
    /// and shows `kind`.
    pub fn note_capture(&self, path: &str, resource_id: Option<&str>, kind: &DeliverableKind) {
        let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
        let capture = ProducedFile::Capture(kind.clone());
        produced.insert(produced_key(path), capture.clone());
        if let Some(id) = resource_id.map(str::trim).filter(|id| !id.is_empty()) {
            produced.insert(id.to_string(), capture);
        }
    }

    /// A tool of the request made the file at `path` itself (with
    /// `resource_id`, when it has one): a generated image saved to the
    /// daemon's inbox. A capture already noted keeps what it shows.
    pub fn note_created(&self, path: &str, resource_id: Option<&str>) {
        let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
        produced
            .entry(produced_key(path))
            .or_insert(ProducedFile::Created);
        if let Some(id) = resource_id.map(str::trim).filter(|id| !id.is_empty()) {
            produced
                .entry(id.to_string())
                .or_insert(ProducedFile::Created);
        }
    }

    /// Ownership from evidence of creation: of `absent` (taken before a
    /// call that then succeeded, [`OwnedFolders::absent_write_targets`]),
    /// each path that is now a regular file was made by this request's
    /// work. A file that existed before never joins, and a capture already
    /// noted keeps what it shows. Returns what it claimed.
    pub fn claim_created(&self, absent: &[std::path::PathBuf]) -> Vec<String> {
        let created: Vec<String> = absent
            .iter()
            .filter(|path| std::fs::symlink_metadata(path).is_ok_and(|meta| meta.is_file()))
            .map(|path| path.display().to_string())
            .collect();
        let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
        for path in &created {
            produced
                .entry(produced_key(path))
                .or_insert(ProducedFile::Created);
        }
        created
    }

    /// What the request's work produced at `target` (a path, or a
    /// capture's resource id), when it produced it.
    pub fn get(&self, target: &str) -> Option<ProducedFile> {
        self.0
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .get(&produced_key(target))
            .cloned()
    }

    /// What the capture saved at `path` shows, when one was noted: a later
    /// `send_file` of that path delivers that kind, not a file of its own.
    pub fn capture_kind(&self, path: &str) -> Option<DeliverableKind> {
        match self.get(path)? {
            ProducedFile::Capture(kind) => Some(kind),
            ProducedFile::Created => None,
        }
    }

    /// Every handle noted, each a path or a capture's resource id, with
    /// what it is.
    pub fn entries(&self) -> Vec<(String, ProducedFile)> {
        self.0
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .iter()
            .map(|(key, file)| (key.clone(), file.clone()))
            .collect()
    }

    /// Of the files and resources a call names (its
    /// [`ToolSemantics::named_files`]), the ones this request's work
    /// produced, each as named.
    pub fn named_by(&self, named: &[String]) -> Vec<(String, ProducedFile)> {
        named
            .iter()
            .filter_map(|name| Some((name.clone(), self.get(name)?)))
            .collect()
    }
}

/// The files and resources a call names by its declared facts (see
/// [`ToolSemantics::named_files`]): its path and resource-id target hints,
/// its access manifest's path targets, and its path effects' targets.
pub fn declared_named_files<T: ToolSemantics + ?Sized>(tool: &T, arguments: &str) -> Vec<String> {
    let mut named: Vec<String> = Vec::new();
    let mut add = |value: &str| {
        let value = value.trim();
        if !value.is_empty() && !named.iter().any(|known| known == value) {
            named.push(value.to_string());
        }
    };
    for hint in tool.call_semantics(arguments).target_hints {
        if matches!(
            hint.kind,
            ToolTargetHintKind::Path | ToolTargetHintKind::ResourceId
        ) {
            add(&hint.value);
        }
    }
    let manifest = tool.call_access_manifest(arguments);
    for hint in manifest
        .read_targets
        .iter()
        .chain(manifest.write_targets.iter())
    {
        if hint.kind == ToolTargetHintKind::Path {
            add(&hint.value);
        }
    }
    for key in tool.call_effects(arguments).keys {
        if matches!(
            key.class,
            aidaemon_core::EffectClass::Write
                | aidaemon_core::EffectClass::Delete
                | aidaemon_core::EffectClass::Configuration
        ) {
            add(&key.target);
        }
    }
    named
}

/// A produced file's key, whichever spelling names it: a path as it
/// resolves on disk (when it does), anything else (a resource id) as given.
fn produced_key(target: &str) -> String {
    let expanded = shellexpand::tilde(target.trim()).into_owned();
    dunce::canonicalize(&expanded)
        .map(|path| path.to_string_lossy().into_owned())
        .unwrap_or(expanded)
}

/// The request's produced files, carried in [`ToolCallContext::extensions`]
/// by a host that keeps them.
pub fn produced_files(facts: &ToolCallContext) -> Option<&ProducedFiles> {
    facts.extensions.get::<ProducedFiles>()
}

#[cfg(test)]
mod produced_file_tests {
    use super::{DeliverableKind, ProducedFile, ProducedFiles};

    /// A file a tool made itself (a generated image in the inbox) is the
    /// request's own by its path and by its resource id; a capture noted
    /// at that path keeps what it shows.
    #[test]
    fn a_file_a_tool_made_is_the_requests_own_by_path_and_id() {
        let produced = ProducedFiles::default();
        produced.note_created("/inbox/018d9d29_generated_image.png", Some("res_img"));
        assert_eq!(
            produced.get("/inbox/018d9d29_generated_image.png"),
            Some(ProducedFile::Created)
        );
        assert_eq!(produced.get("res_img"), Some(ProducedFile::Created));
        let page = DeliverableKind::Screenshot {
            page: "demo.ddev.site".to_string(),
        };
        produced.note_capture("/inbox/shot.png", None, &page);
        produced.note_created("/inbox/shot.png", None);
        assert_eq!(produced.capture_kind("/inbox/shot.png"), Some(page));
    }

    /// A capture is found by its path in any spelling and by its resource
    /// id; a file a call created joins, one that existed before does not,
    /// and a capture keeps what it shows.
    #[test]
    fn the_requests_own_files_come_from_evidence() {
        let base = tempfile::tempdir().unwrap();
        let shot = base.path().join("ea19c410_screenshot.png");
        std::fs::write(&shot, b"png").unwrap();
        let page = DeliverableKind::Screenshot {
            page: "claude-drupal.ddev.site".to_string(),
        };
        let produced = ProducedFiles::default();
        produced.note_capture(&shot.display().to_string(), Some("res_1"), &page);
        let spelled = base
            .path()
            .join(".")
            .join("ea19c410_screenshot.png")
            .display()
            .to_string();
        assert_eq!(produced.capture_kind(&spelled), Some(page.clone()));
        assert_eq!(
            produced.get("res_1"),
            Some(ProducedFile::Capture(page.clone()))
        );

        let fresh = base.path().join("report.md");
        let older = base.path().join("notes.md");
        std::fs::write(&older, "x").unwrap();
        let absent = vec![fresh.clone(), shot.clone()];
        std::fs::write(&fresh, "x").unwrap();
        assert_eq!(produced.claim_created(&absent).len(), 2);
        assert_eq!(
            produced.get(&fresh.display().to_string()),
            Some(ProducedFile::Created)
        );
        assert_eq!(
            produced.capture_kind(&shot.display().to_string()),
            Some(page)
        );
        assert_eq!(produced.get(&older.display().to_string()), None);

        let named = produced.named_by(&[older.display().to_string(), fresh.display().to_string()]);
        assert_eq!(named.len(), 1);
        assert_eq!(named[0].1, ProducedFile::Created);
    }
}

/// The owner's trusted file roots for one turn. A path is trusted only when
/// it normalizes without escaping and equals a root or sits below it. A
/// relative path resolves against `cwd` (where the file tools resolve it);
/// without one it is never trusted.
///
/// `owned` are the folders the request's work made for itself
/// ([`OwnedFolders`]): an effect landing there is the work's own
/// ([`Self::holds_effect`]), but what is read there is not trusted for it.
pub struct TrustRoots<'a> {
    roots: &'a [String],
    owned: &'a [String],
    cwd: Option<&'a str>,
}

impl<'a> TrustRoots<'a> {
    pub fn new(roots: &'a [String]) -> Self {
        Self {
            roots,
            owned: &[],
            cwd: None,
        }
    }

    /// The folders the request's work made for itself.
    pub fn with_owned(mut self, owned: &'a [String]) -> Self {
        self.owned = owned;
        self
    }

    /// Resolve relative paths against `cwd` (an absolute directory).
    pub fn with_cwd(mut self, cwd: Option<&'a str>) -> Self {
        self.cwd = cwd;
        self
    }

    /// The same roots with relative paths resolved against `cwd` instead
    /// (a call that runs in its own directory).
    pub fn anchored_at<'b>(&'b self, cwd: Option<&'b str>) -> TrustRoots<'b> {
        TrustRoots {
            roots: self.roots,
            owned: self.owned,
            cwd,
        }
    }

    /// Whether an effect (a change, a delete) on `path` stays with the
    /// owner's own things: inside a trusted root, or inside a folder the
    /// request's work made for itself. Never a statement about trusting
    /// what is read there ([`Self::contains`] is).
    pub fn holds_effect(&self, path: &str) -> bool {
        if self.contains(path) {
            return true;
        }
        let resolved = match self.cwd {
            Some(cwd) if !is_absolute_or_home(path) => {
                format!("{}/{}", cwd.trim_end_matches('/'), path.trim())
            }
            _ => path.to_string(),
        };
        within_owned(&resolved, self.owned)
    }

    /// Whether `path` is inside a folder the request's work made for
    /// itself (not merely inside a trusted root).
    pub fn owns(&self, path: &str) -> bool {
        within_owned(path, self.owned)
    }

    /// The directory relative paths resolve against, if any.
    pub fn cwd(&self) -> Option<&str> {
        self.cwd
    }

    pub fn contains(&self, path: &str) -> bool {
        let resolved = match self.cwd {
            Some(cwd) if !is_absolute_or_home(path) => {
                format!("{}/{}", cwd.trim_end_matches('/'), path.trim())
            }
            _ => path.to_string(),
        };
        let Some(path) = resolve_absolute(&resolved) else {
            return false;
        };
        self.roots
            .iter()
            .any(|root| resolve_absolute(root).is_some_and(|root| path.starts_with(&root)))
    }
}

/// Output trust of a file read: the owner's own files (inside the trusted
/// roots) are `Trusted`; anything else, or a call whose first present path
/// argument in `keys` is missing, is someone else's content.
pub fn file_output_trust(
    arguments: &str,
    keys: &[&str],
    roots: &TrustRoots<'_>,
) -> aidaemon_core::SourceTrust {
    let args = serde_json::from_str::<Value>(arguments).ok();
    let path = args.as_ref().and_then(|args| {
        keys.iter()
            .find_map(|key| args.get(*key).and_then(Value::as_str))
    });
    match path {
        Some(path) if roots.contains(path) => aidaemon_core::SourceTrust::Trusted,
        _ => aidaemon_core::SourceTrust::Untrusted,
    }
}

/// Expand `~`, then resolve the path the way the filesystem will: every
/// existing prefix through its symlinks (a link inside a root that points
/// elsewhere leaves the root), the rest lexically. `None` for a relative
/// path or one whose `..` climbs above the root.
fn resolve_absolute(path: &str) -> Option<std::path::PathBuf> {
    use std::path::{Component, PathBuf};
    let expanded = shellexpand::tilde(path.trim()).into_owned();
    let path = std::path::Path::new(&expanded);
    if !path.is_absolute() {
        return None;
    }
    let mut resolved = PathBuf::new();
    let mut existing = true;
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if !resolved.pop() {
                    return None;
                }
            }
            Component::Normal(part) => {
                resolved.push(part);
                if existing {
                    match dunce::canonicalize(&resolved) {
                        Ok(canonical) => resolved = canonical,
                        Err(_) => existing = false,
                    }
                }
            }
            other => resolved.push(other.as_os_str()),
        }
    }
    Some(resolved)
}

fn is_absolute_or_home(path: &str) -> bool {
    let path = path.trim();
    // `has_root`: on Windows `\etc\hosts` is on the current drive, not
    // under the working directory (and, with no drive, never trusted).
    let path_ref = std::path::Path::new(path);
    path.starts_with('~') || path_ref.is_absolute() || path_ref.has_root()
}

/// Validated, canonical tool input. This is the boundary object shared by
/// policy, retry, dispatch, and receipt projection; raw model JSON is not an
/// execution fact.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreparedToolInvocation {
    pub canonical_arguments: String,
    pub semantics: ToolCallSemantics,
    pub access_manifest: ToolCallAccessManifest,
    pub receipt_kind: ToolReceiptKind,
}

/// Produce the single typed invocation object consumed by the execution
/// control plane. Validation deliberately precedes semantics and access
/// derivation so a rejected proposal can never acquire intended effects.
pub fn prepare_invocation<T: ToolSemantics + ?Sized>(
    tool: &T,
    arguments: &str,
) -> Result<PreparedToolInvocation, ToolArgumentContractViolation> {
    let canonical_arguments = tool.canonicalize_arguments(arguments)?;
    tool.validate_arguments(&canonical_arguments)?;
    Ok(PreparedToolInvocation {
        semantics: tool.call_semantics(&canonical_arguments),
        access_manifest: tool.call_access_manifest(&canonical_arguments),
        receipt_kind: tool.receipt_kind(&canonical_arguments),
        canonical_arguments,
    })
}

#[cfg(test)]
mod file_trust_tests {
    use super::{TrustRoots, file_output_trust};
    use aidaemon_core::SourceTrust::{Trusted, Untrusted};

    #[test]
    fn files_inside_the_trusted_roots_are_trusted() {
        let roots = vec!["/tmp/aidaemon-test/ws".to_string()];
        let roots = TrustRoots::new(&roots);
        let keys = ["path", "file_path"];
        assert_eq!(
            file_output_trust(r#"{"path":"/tmp/aidaemon-test/ws/a.txt"}"#, &keys, &roots),
            Trusted
        );
        assert_eq!(
            file_output_trust(
                r#"{"file_path":"/tmp/aidaemon-test/ws/a.txt"}"#,
                &keys,
                &roots
            ),
            Trusted
        );
        assert_eq!(
            file_output_trust(r#"{"path":"/etc/hosts"}"#, &keys, &roots),
            Untrusted
        );
        assert_eq!(file_output_trust(r#"{}"#, &keys, &roots), Untrusted);
        assert_eq!(file_output_trust("not json", &keys, &roots), Untrusted);
    }
}

fn is_zero(value: &usize) -> bool {
    *value == 0
}

#[cfg(test)]
mod local_write_satisfaction_tests {
    use super::ToolMutationEffects as E;

    /// Workspace and derived writes close each other's plans; a source edit
    /// is proven only by a source write.
    #[test]
    fn local_write_labels_satisfy_each_other_except_source() {
        assert!(E::LOCAL_WORKSPACE_WRITE.satisfies(E::LOCAL_DERIVED_WRITE));
        assert!(E::LOCAL_DERIVED_WRITE.satisfies(E::LOCAL_WORKSPACE_WRITE));
        assert!(E::LOCAL_SOURCE_WRITE.satisfies(E::LOCAL_DERIVED_WRITE));
        assert!(E::LOCAL_SOURCE_WRITE.satisfies(E::LOCAL_WORKSPACE_WRITE));
        assert!(!E::LOCAL_WORKSPACE_WRITE.satisfies(E::LOCAL_SOURCE_WRITE));
        assert!(!E::LOCAL_DERIVED_WRITE.satisfies(E::LOCAL_SOURCE_WRITE));
        assert!(!E::LOCAL_WORKSPACE_WRITE.satisfies(E::EXTERNAL_DELIVERY));
    }
}