winx-code-agent 0.2.352

Remote-first Rust MCP runtime with Streamable HTTP, durable PTYs, and guarded agent tools
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
use rmcp::model::{CallToolResult, ContentBlock};
use rmcp::ErrorData as McpError;
use schemars::{JsonSchema, Schema, SchemaGenerator};
use serde::Serialize;
use serde_json::{json, Map, Value};

use crate::errors::WinxError;
use crate::runtime::BashCommandRuntimeResult;
use crate::state::turn::TurnState;
use crate::tools::bash_command::BashCommandState;

/// Machine-readable state of a completed Winx tool invocation.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub(super) enum ToolResultStatus {
    Completed,
    CompletedWithIssues,
    Running,
    AwaitingInput,
    AwaitingApproval,
    NeedsRead,
    NeedsInitialize,
    Conflict,
    RecoveryExhausted,
    NotFound,
    Denied,
    InvalidInput,
    Failed,
}

/// A concrete next tool call, or an instruction when arguments cannot be safely inferred.
#[derive(Clone, Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub(super) struct ToolNextAction {
    pub tool: String,
    pub instruction: String,
    #[schemars(schema_with = "open_object_schema")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<Value>,
}

/// File coverage that must be refreshed before retrying an edit.
#[derive(Clone, Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub(super) struct RequiredRead {
    pub path: String,
    pub ranges: Vec<String>,
}

/// Structured result shared by every Winx tool: authoritative `status`, the
/// delivered text in `output`, and the safe next action.
//
// Text content remains the backwards-compatible human-readable result. Some
// clients expose only this object to the model once a tool advertises an
// `outputSchema` (observed with the ChatGPT MCP connector and Claude Code), so
// `output` carries the delivered text as well instead of leaving the model
// with byte counts alone. Doc comments here become `outputSchema`
// descriptions repeated for every tool in `tools/list`; keep them short.
#[derive(Clone, Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub(super) struct ToolResultEnvelope {
    pub status: ToolResultStatus,
    pub tool: String,
    pub message: String,
    /// The delivered text (command output, file text, diagnostics), joined
    /// from the text content blocks. Omitted for image-only results and for
    /// `CodeMap` results whose `files`/`hits` already carry the symbols.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
    pub retryable: bool,
    pub retry_same_call: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_after_ms: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_action: Option<ToolNextAction>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required_reads: Vec<RequiredRead>,
    #[schemars(schema_with = "open_object_schema")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
}

/// Winx only emits object payloads in these extensible result fields. Avoid
/// schemars' boolean `true` schema for `serde_json::Value`: it is valid JSON
/// Schema, but some MCP clients reject boolean schemas while compiling tools.
fn open_object_schema(_: &mut SchemaGenerator) -> Schema {
    schemars::json_schema!({ "type": "object" })
}

/// `CodeMap` keeps its established top-level fields while adding the shared
/// orchestration metadata. Every code-navigation field is optional because the
/// same schema must also describe a tool-level error result.
#[allow(dead_code)] // schema-only shape consumed by schemars in the MCP catalog
#[derive(Clone, Debug, JsonSchema)]
pub(super) struct CodeMapToolResultEnvelope {
    #[schemars(flatten)]
    pub result: ToolResultEnvelope,
    pub truncated: Option<bool>,
    pub next_cursor: Option<String>,
    pub snapshot_hash: Option<String>,
    pub files_scanned: Option<usize>,
    pub payload_bytes: Option<usize>,
    pub source_kind: Option<String>,
    pub canonical: Option<bool>,
    pub temporary_helper_budget: Option<crate::types::CodeMapTemporaryHelperBudget>,
    pub mode: Option<String>,
    pub files_shown: Option<usize>,
    pub files: Option<Vec<crate::types::OutlineFile>>,
    pub file_extension: Option<String>,
    pub language_supported: Option<bool>,
    pub fallback: Option<crate::types::CodeMapFallback>,
    pub name: Option<String>,
    pub definitions: Option<usize>,
    pub references: Option<usize>,
    pub hits: Option<Vec<crate::types::ReferenceHit>>,
}

/// Convert a domain execution failure into a caller-visible MCP tool error.
/// Only failures that prevent the server from producing a valid tool result use
/// JSON-RPC errors; normal execution failures belong in `CallToolResult.isError`.
pub(super) fn tool_failure(
    tool: &str,
    error: &WinxError,
    arguments: Option<&Value>,
) -> Result<CallToolResult, McpError> {
    if matches!(error, WinxError::SerializationError(_) | WinxError::BashStateLockError(_)) {
        return Err(McpError::internal_error(format!("{tool} failed: {error}"), None));
    }

    let text = match (tool, error) {
        (
            "Initialize",
            WinxError::WorkspaceBindingMismatch { requested_workspace, bound_workspace, .. },
        ) => format!(
            "Initialize rejected: this conversation is already bound to {}. Do not call \
             Initialize again for {}. Keep the existing thread_id/workspace_root pair; an \
             allowed target outside that workspace can be accessed by its absolute path without \
             rebinding. If the user truly intends a different project, start a new conversation \
             or client session.",
            bound_workspace.display(),
            requested_workspace.display()
        ),
        ("Initialize", WinxError::WorkspaceChangeRequiresNewSession { workspace_root }) => {
            format!(
                "Initialize rejected: an existing remote conversation cannot change its project \
                 identity in place to {}. Keep using the current binding for allowed external \
                 paths, or start a new conversation/client session for that project. Do not \
                 repeat this Initialize call.",
                workspace_root.display()
            )
        }
        ("EditFiles", error) if error.is_search_match_conflict() => {
            format!(
                "{tool} failed: {error}\n\nNo file was changed by this call. Winx invalidated \
                 the prior read permit for the conflicting target. Execute the exact ReadFiles \
                 nextAction, then make one corrected EditFiles retry with mode=line_patch using \
                 its returned revision and visible coordinates. Do not retry SEARCH or use \
                 BashCommand, sed, or Python for the ordinary file edit."
            )
        }
        ("FileWriteOrEdit" | "MultiFileEdit", error) if error.is_search_match_conflict() => {
            format!(
                "{tool} failed: {error}\n\nNo file was changed by this call. Winx invalidated \
                 the prior read permit for the conflicting target. Call the exact ReadFiles \
                 nextAction, rebuild SEARCH from the returned current text, and do not retry this \
                 edit unchanged. A shell read does not refresh the edit guard."
            )
        }
        _ => format!("{tool} failed: {error}"),
    };
    let envelope = error_envelope(tool, error, arguments, text.clone());
    let mut result = CallToolResult::error(vec![ContentBlock::text(text)]);
    result.structured_content = serde_json::to_value(envelope).ok();
    Ok(result)
}

/// Attach orchestration metadata to a successful non-Bash result without
/// changing its existing text/image content. `BashCommand` is decorated separately
/// from its runtime-owned typed state.
pub(super) fn decorate_success(tool: &str, arguments: Option<&Value>, result: &mut CallToolResult) {
    if result.is_error == Some(true) || tool == "BashCommand" {
        return;
    }
    if result.structured_content.as_ref().is_some_and(|structured| {
        structured.get("tool").and_then(Value::as_str) == Some(tool)
            && structured.get("status").and_then(Value::as_str).is_some()
    }) {
        return;
    }

    let existing = result.structured_content.take();
    let output = content_text(result).filter(|_| {
        !existing
            .as_ref()
            .and_then(Value::as_object)
            .is_some_and(|navigation| code_map_symbols_are_structured(tool, navigation))
    });
    let text = output.clone().unwrap_or_default();
    let mut data = safe_success_data(tool, arguments, &text, false);
    if let Some(existing) = existing.as_ref() {
        if matches!(
            tool,
            "Initialize"
                | "ReadFiles"
                | "FileWriteOrEdit"
                | "MultiFileEdit"
                | "UndoEdit"
                | "ApplyPatch"
                | "EditFiles"
        ) {
            if let Value::Object(metadata) = existing {
                for (key, value) in metadata {
                    if tool == "Initialize"
                        && matches!(key.as_str(), "thread_id" | "workspace_root")
                    {
                        // The handler reports the bound session identity
                        // (normalized thread_id, canonical workspace_root);
                        // it must beat the raw argument echo copied above.
                        data.insert(key.clone(), value.clone());
                    } else {
                        data.entry(key.clone()).or_insert_with(|| value.clone());
                    }
                }
            } else {
                data.insert("result".to_string(), existing.clone());
            }
        } else if tool != "CodeMap" {
            data.insert("result".to_string(), existing.clone());
        }
    }

    let envelope = ToolResultEnvelope {
        status: ToolResultStatus::Completed,
        tool: tool.to_string(),
        message: success_message(tool, ToolResultStatus::Completed),
        output,
        error_code: None,
        retryable: false,
        retry_same_call: false,
        retry_after_ms: None,
        next_action: None,
        required_reads: Vec::new(),
        data: (!data.is_empty()).then_some(Value::Object(data)),
    };

    let Ok(mut value) = serde_json::to_value(envelope) else {
        result.structured_content = existing;
        return;
    };
    if tool == "CodeMap" {
        if let (Value::Object(target), Some(Value::Object(source))) = (&mut value, existing) {
            for (key, item) in source {
                target.entry(key).or_insert(item);
            }
        }
    }
    result.structured_content = Some(value);
}

/// Add file-mutation metadata from the normalized domain context. Legacy wire
/// shapes intentionally are not inspected here, so every edit surface reports
/// the same resolved targets and operation semantics.
pub(super) fn attach_prepared_edit_context(
    result: &mut CallToolResult,
    prepared: &crate::tools::edit_files::PreparedEditContext,
) {
    let Some(Value::Object(envelope)) = result.structured_content.as_mut() else { return };
    let data = envelope.entry("data").or_insert_with(|| Value::Object(Map::new()));
    let Some(data) = data.as_object_mut() else { return };
    let target_paths = prepared.target_paths();
    data.insert("file_count".to_string(), json!(target_paths.len()));
    data.insert("file_paths".to_string(), json!(target_paths));
    if let Some(path) = target_paths.first().filter(|_| target_paths.len() == 1) {
        data.insert("file_path".to_string(), Value::String(path.clone()));
    }
    data.insert(
        "operation".to_string(),
        Value::String(prepared.command.operation().as_str().to_string()),
    );
    data.insert(
        "edit_modes".to_string(),
        Value::Array(
            prepared
                .command
                .modes()
                .into_iter()
                .map(|mode| Value::String(mode.as_str().to_string()))
                .collect(),
        ),
    );
}

/// Render verification guidance with committed-edit state before diagnostic output.
fn edit_verification_presentation(
    tool: &str,
    edit_text: &str,
    verification_text: &str,
    verification_error: bool,
    active: bool,
    nested_status: &str,
    exit_code: Option<i64>,
) -> (String, String) {
    let status_label = if verification_error {
        "completed_with_issues"
    } else if active {
        nested_status
    } else {
        "completed"
    };
    let message = if verification_error {
        format!(
            "{tool} applied the edit, but verification failed. The edit remains applied; do not \
             repeat the original edit. Diagnose the verification output and make only corrective \
             changes."
        )
    } else if active {
        format!("{tool} applied the edit; verification is still {status_label}.")
    } else {
        format!("{tool} applied the edit and verification completed.")
    };
    let summary = if verification_error {
        exit_code.map_or_else(
            || "EDIT APPLIED. Verification failed; do not repeat the original edit.".to_string(),
            |code| {
                format!(
                    "EDIT APPLIED. Verification failed with exit code {code}; do not repeat the \
                     original edit."
                )
            },
        )
    } else if active {
        format!("Verification is still {status_label}.")
    } else {
        exit_code.map_or_else(
            || "Verification completed.".to_string(),
            |code| format!("Verification completed with exit code {code}."),
        )
    };
    let combined_text = if verification_error && verification_text.trim().is_empty() {
        format!("{summary}\n\n{edit_text}")
    } else if verification_error {
        format!("{summary}\n\n{edit_text}\n\n{verification_text}")
    } else if verification_text.trim().is_empty() {
        format!("{edit_text}\n\n{summary}")
    } else {
        format!("{edit_text}\n\n{summary}\n{verification_text}")
    };
    (message, combined_text)
}

pub(super) struct VerificationRecovery {
    pub id: String,
    pub tool: &'static str,
    pub arguments: Value,
}

/// Combine an already-applied edit with its optional foreground verification.
/// The command remains a nested Bash result, while the outer status makes it
/// explicit that a failed verification does not roll the edit back.
pub(super) fn edit_verification_result(
    tool: &str,
    arguments: Option<&Value>,
    edit_text: &str,
    verification: CallToolResult,
    recovery: &VerificationRecovery,
) -> CallToolResult {
    let verification_text = result_text(&verification);
    let verification_is_error = verification.is_error == Some(true);
    let nested = verification.structured_content.unwrap_or_else(|| {
        json!({
            "status": if verification_is_error { "failed" } else { "completed" },
            "tool": "BashCommand",
            "message": "Verification returned no structured result."
        })
    });
    let nested_status = nested.get("status").and_then(Value::as_str).unwrap_or("failed");
    let exit_code =
        nested.get("data").and_then(|data| data.get("exit_code")).and_then(Value::as_i64);
    let nonzero_exit = exit_code.is_some_and(|code| code != 0);
    let verification_error = verification_is_error || nonzero_exit;
    let active = matches!(nested_status, "running" | "awaiting_input" | "awaiting_approval");
    let outer_status = if verification_error {
        ToolResultStatus::CompletedWithIssues
    } else if active {
        match nested_status {
            "running" => ToolResultStatus::Running,
            "awaiting_input" => ToolResultStatus::AwaitingInput,
            "awaiting_approval" => ToolResultStatus::AwaitingApproval,
            _ => ToolResultStatus::Completed,
        }
    } else {
        ToolResultStatus::Completed
    };
    let (message, combined_text) = edit_verification_presentation(
        tool,
        edit_text,
        &verification_text,
        verification_error,
        active,
        nested_status,
        exit_code,
    );

    let mut data = safe_success_data(tool, arguments, &combined_text, false);
    data.insert("edit_applied".to_string(), Value::Bool(true));
    data.insert("original_edit_retryable".to_string(), Value::Bool(false));
    data.insert("follow_up_required".to_string(), Value::Bool(verification_error || active));
    data.insert(
        "verification_status".to_string(),
        Value::String(if verification_error { "failed" } else { nested_status }.to_string()),
    );
    if !active {
        data.insert("verification_passed".to_string(), Value::Bool(!verification_error));
    }
    data.insert("verification".to_string(), nested.clone());
    data.insert("verification_id".to_string(), Value::String(recovery.id.clone()));
    if let Some(exit_code) = exit_code {
        data.insert("verification_exit_code".to_string(), json!(exit_code));
    }

    let mut envelope = json!({
        "status": outer_status,
        "tool": tool,
        "message": message,
        "retryable": if verification_error {
            false
        } else {
            nested.get("retryable").and_then(Value::as_bool).unwrap_or(false)
        },
        "retrySameCall": false,
        "requiredReads": [],
        "data": data,
    });
    if verification_error {
        let nested_code =
            nested.get("errorCode").and_then(Value::as_str).unwrap_or("execution_failed");
        envelope["errorCode"] = Value::String(if nonzero_exit {
            "verification_failed".to_string()
        } else {
            format!("verification_{nested_code}")
        });
    }
    for key in ["retryAfterMs", "nextAction"] {
        if let Some(value) = nested.get(key) {
            envelope[key] = value.clone();
        }
    }
    if verification_error || active {
        envelope["nextAction"] = json!({
            "tool": recovery.tool,
            "instruction": if active {
                "The edit is already applied and verification is still active. Poll these exact receipt-bound verification arguments; never issue a generic status_check or repeat the original edit."
            } else {
                "The edit is already applied. Diagnose the output and make only corrective changes. After that, execute these exact receipt-bound verification arguments; never repeat the original edit."
            },
            "arguments": recovery.arguments
        });
    }

    // Once the edit committed, reporting an MCP tool error is misleading: many
    // agents retry the entire edit and create SEARCH-conflict loops. Verification
    // remains explicit machine-readable follow-up state, while the committed side
    // effect is reported as a successful tool delivery.
    let mut result = CallToolResult::success(vec![ContentBlock::text(combined_text)]);
    result.structured_content = Some(envelope);
    result
}

/// Present a verification retry as its own operation. A non-zero check is a
/// `VerifyEdit` failure, never a reason to replay the already-committed edit.
pub(super) fn verify_edit_result(
    arguments: Option<&Value>,
    verification_id: &str,
    verification: CallToolResult,
) -> CallToolResult {
    let verification_text = result_text(&verification);
    let verification_is_error = verification.is_error == Some(true);
    let nested = verification.structured_content.unwrap_or_else(|| {
        json!({
            "status": if verification_is_error { "failed" } else { "completed" },
            "tool": "BashCommand",
            "message": "Verification returned no structured result."
        })
    });
    let nested_status = nested.get("status").and_then(Value::as_str).unwrap_or("failed");
    let exit_code =
        nested.get("data").and_then(|data| data.get("exit_code")).and_then(Value::as_i64);
    let failed = verification_is_error || exit_code.is_some_and(|code| code != 0);
    let active = matches!(nested_status, "running" | "awaiting_input" | "awaiting_approval");
    let status = if failed {
        ToolResultStatus::Failed
    } else if active {
        match nested_status {
            "running" => ToolResultStatus::Running,
            "awaiting_input" => ToolResultStatus::AwaitingInput,
            "awaiting_approval" => ToolResultStatus::AwaitingApproval,
            _ => ToolResultStatus::Completed,
        }
    } else {
        ToolResultStatus::Completed
    };
    let message = if failed {
        "VerifyEdit failed. The original edit remains applied; fix the reported issue before rerunning this verification."
    } else if active {
        "VerifyEdit is still running."
    } else {
        "VerifyEdit passed. The original edit remains committed."
    };
    let rendered = if failed {
        format!(
            "VERIFICATION FAILED. Do not repeat the original edit. Make corrective changes first.\n\n{verification_text}"
        )
    } else {
        verification_text
    };
    let mut data = safe_success_data("VerifyEdit", arguments, &rendered, false);
    data.insert("verification_id".to_string(), Value::String(verification_id.to_string()));
    data.insert("verification_passed".to_string(), Value::Bool(!failed && !active));
    data.insert("original_edit_retryable".to_string(), Value::Bool(false));
    data.insert("verification".to_string(), nested.clone());
    if let Some(exit_code) = exit_code {
        data.insert("verification_exit_code".to_string(), json!(exit_code));
    }

    let mut envelope = json!({
        "status": status,
        "tool": "VerifyEdit",
        "message": message,
        "retryable": failed,
        "retrySameCall": false,
        "requiredReads": [],
        "data": data,
    });
    if failed {
        envelope["errorCode"] = Value::String("verification_failed".to_string());
        envelope["nextAction"] = json!({
            "tool": "VerifyEdit",
            "instruction": "Do not retry unchanged. Correct the diagnosed code or configuration first, then rerun the same verification receipt.",
            "arguments": arguments
        });
    } else if active {
        if let Some(value) = nested.get("retryAfterMs") {
            envelope["retryAfterMs"] = value.clone();
        }
        envelope["nextAction"] = json!({
            "tool": "VerifyEdit",
            "instruction": "Poll this exact legacy verification receipt; do not use the nested Bash status action and do not repeat the edit.",
            "arguments": arguments
        });
    }

    let mut result = if failed {
        CallToolResult::error(vec![ContentBlock::text(rendered)])
    } else {
        CallToolResult::success(vec![ContentBlock::text(rendered)])
    };
    result.structured_content = Some(envelope);
    result
}

/// Build a `BashCommand` `CallToolResult` exclusively from runtime-owned state.
/// Terminal text is preserved for humans but never parsed for orchestration.
pub(super) fn bash_success_result(
    arguments: Option<&Value>,
    outcome: BashCommandRuntimeResult,
    compact_output: bool,
) -> Result<CallToolResult, McpError> {
    let status = bash_success_status(&outcome.result.state);
    let output_truncated = outcome.output_truncated;
    let next_action = bash_next_action(status, arguments, &outcome.result.state);
    let compact_rendered = compact_output && outcome.compact_output.is_some();
    let rendered_output = if compact_output {
        outcome.compact_output.unwrap_or(outcome.result.output)
    } else {
        outcome.result.output
    };
    let mut data = safe_success_data("BashCommand", arguments, &rendered_output, output_truncated);
    if compact_rendered {
        data.insert("output_format".to_string(), Value::String("compact".to_string()));
    }
    data.insert("cwd".to_string(), Value::String(outcome.result.state.cwd.display().to_string()));
    if let Some(value) = outcome.result.state.exit_code {
        data.insert("exit_code".to_string(), json!(value));
    }
    if let Some(value) = outcome.result.state.background_id.as_ref() {
        data.insert("bg_command_id".to_string(), Value::String(value.clone()));
    }
    if let Some(value) = outcome.result.state.running_for_seconds {
        data.insert("running_for_seconds".to_string(), json!(value));
        data.insert("running_for".to_string(), Value::String(format!("{value} seconds")));
    }
    if let Some(value) = outcome.result.state.turn_state {
        data.insert("turn_state".to_string(), Value::String(value.as_str().to_string()));
    }
    if let Some(value) = outcome.dropped_output_file.as_ref() {
        data.insert(
            "dropped_output_file".to_string(),
            Value::String(value.to_string_lossy().into_owned()),
        );
    }
    if let Some(generation) = outcome.command_generation {
        data.insert("command_generation".to_string(), json!(generation));
    }
    if let Some(token) = outcome.execution_token.as_ref() {
        data.insert(
            "execution_id".to_string(),
            Value::String(format!(
                "{}:{}:{}",
                token.guardian_epoch, token.session_epoch, token.generation
            )),
        );
    }
    let envelope = ToolResultEnvelope {
        status,
        tool: "BashCommand".to_string(),
        message: success_message("BashCommand", status),
        output: Some(rendered_output.clone()),
        error_code: None,
        retryable: false,
        retry_same_call: false,
        retry_after_ms: (status == ToolResultStatus::Running).then_some(1_000),
        next_action,
        required_reads: Vec::new(),
        data: (!data.is_empty()).then_some(Value::Object(data)),
    };
    let structured_content = serde_json::to_value(envelope).map_err(|error| {
        McpError::internal_error(
            format!("failed to serialize typed BashCommand result: {error}"),
            None,
        )
    })?;
    let mut result = CallToolResult::success(vec![ContentBlock::text(rendered_output)]);
    result.structured_content = Some(structured_content);
    Ok(result)
}

/// Attach the post-Bash managed-temp audit. A command that already ran remains
/// a successful command result, but an over-budget session gets an explicit
/// cleanup-required state and future Command actions are blocked by preflight.
pub(super) fn attach_temporary_artifact_usage(
    result: &mut CallToolResult,
    arguments: Option<&Value>,
    usage: &crate::utils::agent_temp::TemporaryArtifactUsage,
) {
    let Some(Value::Object(envelope)) = result.structured_content.as_mut() else { return };
    let data = envelope.entry("data").or_insert_with(|| Value::Object(Map::new())).as_object_mut();
    let Some(data) = data else { return };
    if let Ok(value) = serde_json::to_value(usage) {
        data.insert("temporary_artifact_budget".to_string(), value);
    }
    if !usage.over_budget {
        return;
    }

    data.insert("temporary_artifact_cleanup_required".to_string(), Value::Bool(true));
    let background_id = data.get("bg_command_id").and_then(Value::as_str).map(str::to_string);
    let running = envelope.get("status").and_then(Value::as_str) == Some("running");
    let automatic_cleanup = if usage.stale_pruned_files > 0 {
        format!(
            "Winx already reclaimed {} TTL-expired helper(s) / {} bytes; fresh artifacts were \
             preserved.",
            usage.stale_pruned_files, usage.stale_pruned_bytes
        )
    } else {
        "No eligible TTL-expired helper was removed; fresh artifacts were preserved.".to_string()
    };
    let instruction = if running {
        format!(
            "The running process has exceeded the managed temporary-artifact budget. Interrupt it, \
             then inspect and remove obsolete files beneath $WINX_TEMP_DIR before starting another \
             command. {automatic_cleanup}"
        )
    } else {
        format!(
            "Inspect and remove obsolete files beneath $WINX_TEMP_DIR with a cleanup-only \
             BashCommand. {automatic_cleanup} Ordinary Command actions remain blocked until this \
             session is back under budget."
        )
    };
    envelope.insert(
        "message".to_string(),
        Value::String(if running {
            "BashCommand is running, but its temporary-artifact budget is exceeded.".to_string()
        } else {
            "BashCommand completed, but its temporary-artifact budget is exceeded.".to_string()
        }),
    );
    let next_arguments = running.then(|| {
        let mut action = json!({
            "action_json": {
                "type": "send_specials",
                "send_specials": ["Ctrl-c"],
                "submit": false
            },
            "wait_policy": "return_early"
        });
        copy_session_binding(arguments, &mut action);
        if let Some(background_id) = background_id {
            action["action_json"]["bg_command_id"] = Value::String(background_id);
        }
        action
    });
    let next_action =
        ToolNextAction { tool: "BashCommand".to_string(), instruction, arguments: next_arguments };
    if let Ok(value) = serde_json::to_value(next_action) {
        envelope.insert("nextAction".to_string(), value);
    }

    let thread_id = string_argument(arguments, "thread_id").unwrap_or_default();
    result.content.push(ContentBlock::text(format!(
        "Winx guard: temporary_artifact_dir={} now contains {} files / {} bytes (limits: {} \
         files / {} bytes; largest file {} bytes, limit {}). Stale reclamation removed {} files / \
         {} bytes while preserving fresh artifacts. Inspect and remove remaining obsolete helpers \
         with a cleanup-only BashCommand using thread_id={thread_id}.",
        usage.temporary_artifact_dir.display(),
        usage.session_files,
        usage.session_bytes,
        usage.max_session_files,
        usage.max_session_bytes,
        usage.largest_file_bytes,
        usage.max_file_bytes,
        usage.stale_pruned_files,
        usage.stale_pruned_bytes,
    )));
}

pub(super) fn result_status(result: &CallToolResult) -> String {
    result
        .structured_content
        .as_ref()
        .and_then(|value| value.get("status"))
        .and_then(Value::as_str)
        .unwrap_or(if result.is_error == Some(true) { "failed" } else { "completed" })
        .to_string()
}

pub(super) fn result_size_bytes(result: &CallToolResult) -> usize {
    let content = result
        .content
        .iter()
        .map(|block| {
            block
                .as_text()
                .map_or(0, |text| text.text.len())
                .saturating_add(block.as_image().map_or(0, |image| image.data.len()))
        })
        .fold(0usize, usize::saturating_add);
    content.saturating_add(
        result
            .structured_content
            .as_ref()
            .and_then(|value| serde_json::to_vec(value).ok())
            .map_or(0, |value| value.len()),
    )
}

/// Ensure model-facing recovery never points at a tool this principal cannot
/// call. A hidden compatibility alias is permitted only when its equivalent
/// unified capability is already authorized; runtime authorization remains the
/// final authority.
pub(super) fn enforce_next_action_policy(
    result: &mut CallToolResult,
    policy: crate::tool_policy::ToolPolicy,
) {
    let Some(Value::Object(envelope)) = result.structured_content.as_mut() else { return };
    let Some(next_tool) =
        envelope.get("nextAction").and_then(|action| action.get("tool")).and_then(Value::as_str)
    else {
        return;
    };
    if policy.allows_call(next_tool) {
        return;
    }
    let edit_applied = envelope
        .get("data")
        .and_then(|data| data.get("edit_applied"))
        .and_then(Value::as_bool)
        .unwrap_or(false);
    envelope.remove("nextAction");
    envelope.insert("errorCode".to_string(), Value::String("policy_blocked".to_string()));
    envelope.insert("retryable".to_string(), Value::Bool(false));
    envelope.insert("requiredReads".to_string(), Value::Array(Vec::new()));
    if !edit_applied {
        envelope.insert("status".to_string(), json!(ToolResultStatus::Denied));
        result.is_error = Some(true);
    }
    let data = envelope.entry("data").or_insert_with(|| Value::Object(Map::new()));
    if let Value::Object(data) = data {
        data.insert("follow_up_blocked_by_policy".to_string(), Value::Bool(true));
    }
    let suffix = " Required recovery is unavailable in this request's tool policy; no unauthorized action was emitted.";
    let message = envelope
        .get("message")
        .and_then(Value::as_str)
        .unwrap_or("Tool recovery is blocked by policy.")
        .to_string();
    envelope.insert("message".to_string(), Value::String(format!("{message}{suffix}")));
    result.content.insert(0, ContentBlock::text(format!("POLICY BLOCKED.{suffix}")));
    mirror_text_output(result);
}

fn result_text(result: &CallToolResult) -> String {
    content_text(result).unwrap_or_default()
}

/// Joined text of every text content block, or `None` when the result carries
/// no text block at all (for example an image-only `ReadImage` delivery). An
/// empty command output is still `Some("")`: the block exists, it is just empty.
fn content_text(result: &CallToolResult) -> Option<String> {
    let mut blocks = result
        .content
        .iter()
        .filter_map(|content| content.as_text().map(|text| text.text.as_str()))
        .peekable();
    blocks.peek()?;
    Some(blocks.collect::<Vec<_>>().join("\n"))
}

/// Keep `structuredContent.output` in sync with the text content.
///
/// Typed constructors set `output` eagerly, but the guarantee lives at the
/// delivery boundary: later steps may rewrite the text blocks (policy banners,
/// `ReadFiles` partial output, Task aggregation, redaction) and manual JSON
/// envelopes never set it. Run this after the last such step so a client that
/// reads only `structuredContent` sees what a text-only client sees. The
/// joined text is redacted once more as a whole, so `output` is never less
/// redacted than `content` even when a secret straddles two blocks. Idempotent.
pub(super) fn mirror_text_output(result: &mut CallToolResult) {
    let text = content_text(result);
    let Some(Value::Object(envelope)) = result.structured_content.as_mut() else { return };
    let tool = envelope.get("tool").and_then(Value::as_str).unwrap_or_default();
    if code_map_symbols_are_structured(tool, envelope) {
        envelope.remove("output");
        return;
    }
    match text {
        Some(text) => {
            let text = crate::utils::redact::redact(&text).into_owned();
            envelope.insert("output".to_string(), Value::String(text));
        }
        None => {
            envelope.remove("output");
        }
    }
}

/// A `CodeMap` result whose `files`/`hits` already carry symbols does not
/// mirror its text: that text is a rendering of the same symbols, and the
/// duplicate would double the model-visible payload of the largest responses.
/// Results without symbols keep the mirror, because only the text carries the
/// diagnostic (an unreadable file, an oversized first result, a failure).
fn code_map_symbols_are_structured(tool: &str, structured: &Map<String, Value>) -> bool {
    tool == "CodeMap"
        && ["files", "hits"].iter().any(|key| {
            structured.get(*key).and_then(Value::as_array).is_some_and(|items| !items.is_empty())
        })
}

/// Single delivery boundary for a tool result: redact the text blocks and the
/// structured payload, then mirror the final text into `structuredContent`.
/// Every `CallToolResult` that leaves the server passes through here, including
/// the early returns that bypass the ordinary dispatch pipeline.
pub(super) fn finalize_tool_result(result: &mut CallToolResult) {
    for content in &mut result.content {
        if let ContentBlock::Text(text) = content {
            if let std::borrow::Cow::Owned(scrubbed) = crate::utils::redact::redact(&text.text) {
                text.text = scrubbed;
            }
        }
    }
    if let Some(structured) = result.structured_content.as_mut() {
        crate::utils::redact::redact_json(structured);
    }
    mirror_text_output(result);
}

fn bash_success_status(state: &BashCommandState) -> ToolResultStatus {
    if !state.is_running() {
        return ToolResultStatus::Completed;
    }
    match state.turn_state {
        Some(TurnState::AwaitingApproval) => ToolResultStatus::AwaitingApproval,
        Some(TurnState::AwaitingInput) => ToolResultStatus::AwaitingInput,
        Some(TurnState::Busy | TurnState::Unknown) | None => ToolResultStatus::Running,
    }
}

fn success_message(tool: &str, status: ToolResultStatus) -> String {
    match status {
        ToolResultStatus::Running => format!("{tool} is still running."),
        ToolResultStatus::AwaitingInput => format!("{tool} is waiting for input."),
        ToolResultStatus::AwaitingApproval => format!("{tool} is waiting for approval."),
        _ => format!("{tool} completed."),
    }
}

fn bash_next_action(
    status: ToolResultStatus,
    arguments: Option<&Value>,
    bash_state: &BashCommandState,
) -> Option<ToolNextAction> {
    match status {
        ToolResultStatus::Running => {
            let mut action = json!({
                "action_json": {
                    "type": "status_check",
                    "status_check": true
                }
            });
            copy_session_binding(arguments, &mut action);
            if let Some(background_id) = bash_state.background_id.as_ref() {
                action["action_json"]["bg_command_id"] = Value::String(background_id.clone());
            }
            Some(ToolNextAction {
                tool: "BashCommand".to_string(),
                instruction: "Wait for retry_after_ms, then check status. Do not repeat the original command."
                    .to_string(),
                arguments: Some(action),
            })
        }
        ToolResultStatus::AwaitingInput => Some(ToolNextAction {
            tool: "BashCommand".to_string(),
            instruction: "Inspect the returned screen, then use send_text or send_specials with the required input."
                .to_string(),
            arguments: None,
        }),
        ToolResultStatus::AwaitingApproval => Some(ToolNextAction {
            tool: "BashCommand".to_string(),
            instruction: "Do not approve automatically. Ask the user when approval changes permissions, data, or system state."
                .to_string(),
            arguments: None,
        }),
        _ => None,
    }
}

fn safe_success_data(
    tool: &str,
    arguments: Option<&Value>,
    text: &str,
    output_truncated: bool,
) -> Map<String, Value> {
    let mut data = Map::new();
    data.insert("output_bytes".to_string(), json!(text.len()));
    data.insert("output_truncated".to_string(), json!(output_truncated));

    for key in [
        "thread_id",
        "operation",
        "path",
        "name",
        "id",
        "mode_name",
        "any_workspace_path",
        "workspace_root",
    ] {
        if let Some(value) = string_argument(arguments, key) {
            data.insert(key.to_string(), Value::String(value));
        }
    }
    if tool == "ReadImage" {
        if let Some(file_path) = string_argument(arguments, "file_path") {
            data.insert("file_path".to_string(), Value::String(file_path));
        }
    }
    if tool == "ReadFiles" {
        if let Some(files) = arguments
            .and_then(Value::as_object)
            .and_then(|arguments| arguments.get("file_paths"))
            .and_then(Value::as_array)
        {
            data.insert(
                "file_paths".to_string(),
                Value::Array(
                    files.iter().filter_map(Value::as_str).map(|value| json!(value)).collect(),
                ),
            );
        }
    }
    if tool == "BashCommand" {
        if let Some(action) = bash_action(arguments) {
            data.insert("action".to_string(), Value::String(action));
        }
        if let (Some(thread_id), Some(workspace_root)) =
            (string_argument(arguments, "thread_id"), string_argument(arguments, "workspace_root"))
        {
            let temporary_artifact = crate::utils::agent_temp::session_info(
                std::path::Path::new(&workspace_root),
                &thread_id,
            );
            data.insert(
                "temporary_artifact_dir".to_string(),
                Value::String(temporary_artifact.directory.to_string_lossy().into_owned()),
            );
            data.insert(
                "temporary_artifact_env".to_string(),
                Value::String("WINX_TEMP_DIR".into()),
            );
        }
    }
    data
}

#[allow(clippy::too_many_lines)] // exhaustive error taxonomy is clearer in one match
fn error_envelope(
    tool: &str,
    error: &WinxError,
    arguments: Option<&Value>,
    text: String,
) -> ToolResultEnvelope {
    let classified_error = error.edit_source();
    let mut status = ToolResultStatus::Failed;
    let mut error_code = "execution_failed".to_string();
    let mut retryable = false;
    let mut retry_after_ms = None;
    let mut next_action = None;
    let mut required_reads = Vec::new();

    match classified_error {
        WinxError::BashStateNotInitialized => {
            status = ToolResultStatus::NeedsInitialize;
            error_code = "not_initialized".to_string();
            retryable = true;
            next_action = Some(missing_session_initialize_action(tool, arguments));
        }
        WinxError::WorkspaceBindingRequired { .. } => {
            status = ToolResultStatus::NeedsInitialize;
            error_code = "workspace_binding_required".to_string();
            retryable = true;
            next_action = Some(ToolNextAction {
                tool: "Initialize".to_string(),
                instruction: "Initialize the intended workspace once, then copy the returned thread_id/workspace_root pair into every later call."
                    .to_string(),
                arguments: None,
            });
        }
        WinxError::WorkspaceThreadMismatch { workspace_root, .. } => {
            status = ToolResultStatus::Conflict;
            error_code = "workspace_thread_mismatch".to_string();
            retryable = true;
            next_action = Some(initialize_workspace_action(workspace_root));
        }
        WinxError::WorkspaceBindingMismatch { .. } if tool == "Initialize" => {
            status = ToolResultStatus::Conflict;
            error_code = "initialize_workspace_already_bound".to_string();
            retryable = false;
        }
        WinxError::WorkspaceBindingMismatch { requested_workspace, .. } => {
            status = ToolResultStatus::Conflict;
            error_code = "workspace_binding_mismatch".to_string();
            retryable = true;
            next_action = Some(initialize_workspace_action(requested_workspace));
        }
        WinxError::WorkspaceChangeRequiresNewSession { .. } => {
            status = ToolResultStatus::Conflict;
            error_code = "workspace_change_requires_new_session".to_string();
            retryable = false;
        }
        WinxError::CommandAlreadyRunning { .. } => {
            status = ToolResultStatus::Running;
            error_code = "command_already_running".to_string();
            retryable = true;
            retry_after_ms = Some(1_000);
            next_action = Some(status_check_action(arguments));
        }
        WinxError::TemporaryArtifactPolicy { temporary_artifact_dir, .. } => {
            status = ToolResultStatus::InvalidInput;
            error_code = "temporary_artifact_policy".to_string();
            retryable = true;
            next_action = Some(if tool == "CodeMap" {
                ToolNextAction {
                    tool: "ReadFiles".to_string(),
                    instruction: "Use the canonical source or a targeted range from an existing \
                                  file. For plain-text search use rg via BashCommand. Do not create \
                                  or map another carrier."
                        .to_string(),
                    arguments: None,
                }
            } else {
                ToolNextAction {
                    tool: tool.to_string(),
                    instruction: format!(
                        "Correct the helper path or content using temporary_artifact_dir `{}`; use \
                         a short descriptive path and do not repeat the rejected call unchanged.",
                        temporary_artifact_dir.display()
                    ),
                    arguments: None,
                }
            });
        }
        WinxError::TemporaryArtifactBudgetExceeded { temporary_artifact_dir, .. } => {
            status = ToolResultStatus::InvalidInput;
            error_code = "temporary_artifact_budget_exceeded".to_string();
            retryable = true;
            next_action = Some(ToolNextAction {
                tool: "BashCommand".to_string(),
                instruction: format!(
                    "Inspect and remove obsolete files beneath `{}` using only inspection/cleanup \
                     commands. Ordinary commands remain blocked until the active session is back \
                     under budget; do not repeat the rejected command unchanged.",
                    temporary_artifact_dir.display()
                ),
                arguments: None,
            });
        }
        WinxError::InvalidWaitPolicyForAction { .. } => {
            status = ToolResultStatus::InvalidInput;
            error_code = "wait_policy_incompatible_with_action".to_string();
            retryable = true;
            let mut corrected = arguments.cloned();
            if let Some(Value::Object(arguments)) = corrected.as_mut() {
                arguments
                    .insert("wait_policy".to_string(), Value::String("return_early".to_string()));
            }
            next_action = Some(ToolNextAction {
                tool: "BashCommand".to_string(),
                instruction: "Retry the action with wait_policy=return_early. Reserve \
                              until_complete for a finite foreground Command action only."
                    .to_string(),
                arguments: corrected,
            });
        }
        WinxError::DerivedCodeMapBudget { .. } => {
            status = ToolResultStatus::InvalidInput;
            error_code = "derived_code_map_budget_exhausted".to_string();
            retryable = true;
            next_action = Some(ToolNextAction {
                tool: "ReadFiles".to_string(),
                instruction: "Stop creating or mapping temporary carriers. Reuse prior results, \
                              run CodeMap on canonical source, or read only the exact canonical \
                              ranges needed; use rg via BashCommand for plain-text search."
                    .to_string(),
                arguments: None,
            });
        }
        WinxError::PathSecurityError { .. } | WinxError::CommandNotAllowed(_) => {
            status = ToolResultStatus::Denied;
            error_code = "operation_denied".to_string();
        }
        WinxError::WorkspacePathError(_) | WinxError::BackgroundSessionNotFound(_) => {
            status = ToolResultStatus::NotFound;
            error_code = "target_not_found".to_string();
        }
        WinxError::ThreadIdMismatch(_) => {
            status = ToolResultStatus::Conflict;
            error_code = "thread_id_mismatch".to_string();
        }
        WinxError::ParameterValidationError { .. }
        | WinxError::MissingParameterError { .. }
        | WinxError::NullValueError { .. }
        | WinxError::ArgumentParseError(_)
        | WinxError::JsonParseError(_)
        | WinxError::DeserializationError(_)
        | WinxError::InvalidInput(_)
        | WinxError::ParseError(_)
        | WinxError::SearchReplaceSyntaxError(_)
        | WinxError::SearchReplaceSyntaxErrorDetailed { .. }
        | WinxError::EmptyInteractiveInput { .. }
        | WinxError::InteractiveTargetNotRunning(_)
        | WinxError::NoActiveCommand(_) => {
            status = ToolResultStatus::InvalidInput;
            error_code = "invalid_tool_input".to_string();
            retryable = true;
        }
        WinxError::RecoverableSuggestionError { .. } => {
            retryable = true;
            error_code = "recoverable_failure".to_string();
        }
        WinxError::CommandTimeout { timeout_seconds, .. } => {
            error_code = "command_timeout".to_string();
            retryable = true;
            retry_after_ms = Some(timeout_seconds.saturating_mul(1_000));
        }
        _ => {}
    }

    if let Some(plan) = super::recovery::classify(tool, error, arguments) {
        status = plan.status;
        error_code = plan.error_code.to_string();
        retryable = plan.retryable;
        retry_after_ms = plan.retry_after_ms;
        next_action = plan.next_action;
        required_reads = plan.required_reads;
    }

    let mut data = Map::new();
    if let Some(thread_id) = string_argument(arguments, "thread_id") {
        data.insert("thread_id".to_string(), Value::String(thread_id));
    }
    if let Some(workspace_root) = string_argument(arguments, "workspace_root") {
        data.insert("workspace_root".to_string(), Value::String(workspace_root));
    }
    if let WinxError::WorkspaceBindingMismatch { requested_workspace, bound_workspace, .. } =
        classified_error
    {
        data.insert(
            "bound_workspace".to_string(),
            Value::String(bound_workspace.to_string_lossy().into_owned()),
        );
        data.insert(
            "requested_workspace".to_string(),
            Value::String(requested_workspace.to_string_lossy().into_owned()),
        );
        if tool == "Initialize" {
            data.insert("continue_with_bound_session".to_string(), Value::Bool(true));
            data.insert("external_targets_require_reinitialize".to_string(), Value::Bool(false));
        }
    }
    if let WinxError::TemporaryArtifactPolicy { path, temporary_artifact_dir, .. } =
        classified_error
    {
        data.insert(
            "rejected_path".to_string(),
            Value::String(path.to_string_lossy().into_owned()),
        );
        data.insert(
            "temporary_artifact_dir".to_string(),
            Value::String(temporary_artifact_dir.to_string_lossy().into_owned()),
        );
    }
    if let WinxError::TemporaryArtifactBudgetExceeded {
        temporary_artifact_dir,
        total_bytes,
        max_total_bytes,
        session_bytes,
        max_session_bytes,
        session_files,
        max_session_files,
        largest_file_bytes,
        max_file_bytes,
    } = classified_error
    {
        data.insert(
            "temporary_artifact_dir".to_string(),
            Value::String(temporary_artifact_dir.to_string_lossy().into_owned()),
        );
        data.insert("total_bytes".to_string(), json!(total_bytes));
        data.insert("max_total_bytes".to_string(), json!(max_total_bytes));
        data.insert("session_bytes".to_string(), json!(session_bytes));
        data.insert("max_session_bytes".to_string(), json!(max_session_bytes));
        data.insert("session_files".to_string(), json!(session_files));
        data.insert("max_session_files".to_string(), json!(max_session_files));
        data.insert("largest_file_bytes".to_string(), json!(largest_file_bytes));
        data.insert("max_file_bytes".to_string(), json!(max_file_bytes));
        data.insert("temporary_artifact_cleanup_required".to_string(), Value::Bool(true));
    }
    if let WinxError::InvalidWaitPolicyForAction { wait_policy, action } = classified_error {
        data.insert("wait_policy".to_string(), Value::String(wait_policy.clone()));
        data.insert("action".to_string(), Value::String(action.clone()));
    }
    if let WinxError::DerivedCodeMapBudget {
        path,
        temporary_artifact_dir,
        calls_used,
        calls_limit,
        unique_files_used,
        unique_files_limit,
        ..
    } = classified_error
    {
        data.insert(
            "rejected_path".to_string(),
            Value::String(path.to_string_lossy().into_owned()),
        );
        data.insert(
            "temporary_artifact_dir".to_string(),
            Value::String(temporary_artifact_dir.to_string_lossy().into_owned()),
        );
        data.insert("calls_used".to_string(), json!(calls_used));
        data.insert("calls_limit".to_string(), json!(calls_limit));
        data.insert("unique_files_used".to_string(), json!(unique_files_used));
        data.insert("unique_files_limit".to_string(), json!(unique_files_limit));
    }
    if error.is_search_match_conflict() {
        data.insert("edit_applied".to_string(), Value::Bool(false));
        data.insert("fresh_read_required".to_string(), Value::Bool(true));
        data.insert("read_permit_invalidated".to_string(), Value::Bool(true));
        if tool == "EditFiles" {
            data.insert(
                "recommended_edit_mode".to_string(),
                Value::String("line_patch".to_string()),
            );
            data.insert("ordinary_shell_edit_fallback".to_string(), Value::Bool(false));
        }
    }
    ToolResultEnvelope {
        status,
        tool: tool.to_string(),
        output: Some(text.clone()),
        message: text,
        error_code: Some(error_code),
        retryable,
        retry_same_call: false,
        retry_after_ms,
        next_action,
        required_reads,
        data: (!data.is_empty()).then_some(Value::Object(data)),
    }
}

fn status_check_action(arguments: Option<&Value>) -> ToolNextAction {
    let mut value = json!({
        "action_json": {
            "type": "status_check",
            "status_check": true
        }
    });
    copy_session_binding(arguments, &mut value);
    ToolNextAction {
        tool: "BashCommand".to_string(),
        instruction: "Check the running command instead of submitting the original command again."
            .to_string(),
        arguments: Some(value),
    }
}

fn initialize_workspace_action(workspace_root: &std::path::Path) -> ToolNextAction {
    ToolNextAction {
        tool: "Initialize".to_string(),
        instruction: "Initialize this intended project as a separate coherent session, then use the returned thread_id/workspace_root pair."
            .to_string(),
        arguments: Some(json!({
            "type": "first_call",
            "any_workspace_path": workspace_root.to_string_lossy(),
            "initial_files_to_read": [],
            "mode_name": "wcgw",
            "thread_id": ""
        })),
    }
}

fn missing_session_initialize_action(tool: &str, arguments: Option<&Value>) -> ToolNextAction {
    let corrected_arguments = if tool == "Initialize" {
        arguments.and_then(Value::as_object).map(|arguments| {
            let mut corrected = arguments.clone();
            corrected.insert("type".to_string(), Value::String("first_call".to_string()));
            Value::Object(corrected)
        })
    } else {
        string_argument(arguments, "workspace_root").map(|workspace_root| {
            let mut corrected = json!({
                "type": "first_call",
                "any_workspace_path": workspace_root,
                "initial_files_to_read": [],
                "mode_name": "wcgw"
            });
            if let Some(thread_id) = string_argument(arguments, "thread_id") {
                corrected["thread_id"] = Value::String(thread_id);
            }
            corrected
        })
    };
    ToolNextAction {
        tool: "Initialize".to_string(),
        instruction: "Call this corrected first_call exactly once for the intended workspace, preserve the returned thread_id/workspace_root pair, then retry the interrupted operation. Do not retry the prior reset, mode change, or stateful tool first."
            .to_string(),
        arguments: corrected_arguments,
    }
}

fn copy_session_binding(arguments: Option<&Value>, target: &mut Value) {
    for key in ["thread_id", "workspace_root"] {
        if let Some(value) = string_argument(arguments, key) {
            target[key] = Value::String(value);
        }
    }
}

fn bash_action(arguments: Option<&Value>) -> Option<String> {
    let arguments = arguments?.as_object()?;
    let fallback = Value::Object(arguments.clone());
    let action = arguments.get("action_json").unwrap_or(&fallback);
    match action {
        Value::Object(action) => {
            action.get("type").and_then(Value::as_str).map(ToString::to_string).or_else(|| {
                [
                    "command",
                    "status_check",
                    "send_text",
                    "send_specials",
                    "send_ascii",
                    "screen",
                    "wait_for_turn",
                ]
                .into_iter()
                .find(|kind| action.contains_key(*kind))
                .map(ToString::to_string)
            })
        }
        Value::String(_) => Some("command".to_string()),
        _ => None,
    }
}

fn string_argument(arguments: Option<&Value>, key: &str) -> Option<String> {
    arguments?
        .as_object()?
        .get(key)?
        .as_str()
        .filter(|value| !value.is_empty())
        .map(ToString::to_string)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]
    use super::*;

    fn exited_bash_result(output: &str) -> BashCommandRuntimeResult {
        BashCommandRuntimeResult {
            result: crate::tools::bash_command::BashCommandResult {
                output: output.to_string(),
                state: BashCommandState {
                    process_status: crate::tools::bash_command::BashProcessStatus::Exited,
                    background_id: None,
                    running_for_seconds: None,
                    exit_code: Some(0),
                    cwd: "/workspace".into(),
                    turn_state: None,
                },
            },
            compact_output: None,
            command_generation: Some(1),
            execution_token: None,
            generation_bound_actions: false,
            dropped_output_file: None,
            output_truncated: false,
        }
    }

    #[test]
    fn bash_success_mirrors_rendered_output_for_structured_only_clients() {
        let result = bash_success_result(
            Some(&json!({
                "thread_id": "thread",
                "workspace_root": "/workspace",
                "action_json": {"type": "command", "command": "printf WINX_OK"}
            })),
            exited_bash_result("WINX_OK"),
            false,
        )
        .expect("typed BashCommand result");
        let text = result.content[0].as_text().expect("text block").text.clone();
        let structured = result.structured_content.expect("structured success");
        assert_eq!(structured["status"], "completed");
        assert_eq!(structured["output"], "WINX_OK");
        assert_eq!(structured["output"], text);
        assert_eq!(structured["data"]["output_bytes"], 7);
    }

    #[test]
    fn empty_command_output_is_mirrored_as_an_empty_string() {
        let result = bash_success_result(None, exited_bash_result(""), false)
            .expect("typed BashCommand result");
        let structured = result.structured_content.expect("structured success");
        assert_eq!(structured["output"], "");
    }

    #[test]
    fn decorate_success_mirrors_joined_text_and_omits_output_for_images() {
        let mut result = CallToolResult::success(vec![
            ContentBlock::text("first"),
            ContentBlock::text("second"),
        ]);
        decorate_success("ReadFiles", Some(&json!({"thread_id": "thread"})), &mut result);
        let structured = result.structured_content.expect("structured success");
        assert_eq!(structured["output"], "first\nsecond");
        assert_eq!(structured["data"]["output_bytes"], "first\nsecond".len());

        let mut image = CallToolResult::success(vec![ContentBlock::image("AAAA", "image/png")]);
        image.structured_content = Some(json!({"content_fingerprint": "abc"}));
        decorate_success("ReadImage", None, &mut image);
        let structured = image.structured_content.expect("structured image result");
        assert_eq!(structured["status"], "completed");
        assert!(structured.get("output").is_none(), "{structured}");
        assert_eq!(structured["data"]["result"]["content_fingerprint"], "abc");
    }

    #[test]
    fn initialize_reports_the_bound_session_identity_over_argument_echoes() {
        let mut result = CallToolResult::success(vec![ContentBlock::text(
            "Use thread_id=ws_bound for all winx tool calls.",
        )]);
        result.structured_content = Some(json!({
            "thread_id": "ws_bound",
            "workspace_root": "/canonical/workspace",
            "initialize_transition": "created"
        }));
        decorate_success(
            "Initialize",
            Some(&json!({
                "thread_id": " client-thread ",
                "workspace_root": "/requested/workspace",
                "any_workspace_path": "/requested/workspace"
            })),
            &mut result,
        );
        let structured = result.structured_content.expect("structured Initialize result");
        assert_eq!(structured["data"]["thread_id"], "ws_bound");
        assert_eq!(structured["data"]["workspace_root"], "/canonical/workspace");
        assert_eq!(structured["data"]["any_workspace_path"], "/requested/workspace");
        assert_eq!(structured["data"]["initialize_transition"], "created");
        assert_eq!(structured["output"], "Use thread_id=ws_bound for all winx tool calls.");
    }

    #[test]
    fn tool_failure_mirrors_its_text_into_output() {
        let result = tool_failure(
            "BashCommand",
            &WinxError::BashStateNotInitialized,
            Some(&json!({"thread_id": "thread"})),
        )
        .expect("tool-level error");
        let text = result.content[0].as_text().expect("text block").text.clone();
        let structured = result.structured_content.expect("structured error");
        assert_eq!(structured["status"], "needs_initialize");
        assert_eq!(structured["output"], text);
        assert_eq!(structured["message"], text);
    }

    #[test]
    fn code_map_omits_output_only_when_its_symbols_are_structured() {
        let mut symbols =
            CallToolResult::success(vec![ContentBlock::text("src/lib.rs\n  1 fn main")]);
        symbols.structured_content = Some(json!({
            "mode": "file",
            "files": [{"file": "src/lib.rs", "symbols": [{"name": "main", "kind": "fn", "line": 1}]}],
            "payload_bytes": 1
        }));
        decorate_success("CodeMap", None, &mut symbols);
        let structured = symbols.structured_content.as_ref().expect("structured CodeMap result");
        assert_eq!(structured["status"], "completed");
        assert!(structured.get("output").is_none(), "{structured}");
        assert_eq!(structured["mode"], "file");
        finalize_tool_result(&mut symbols);
        assert!(symbols.structured_content.expect("structured")["output"].is_null());

        let diagnostic = "Could not outline src/broken.rs: permission denied";
        let mut unreadable = CallToolResult::success(vec![ContentBlock::text(diagnostic)]);
        unreadable.structured_content =
            Some(json!({"mode": "file", "files": [], "payload_bytes": 1}));
        decorate_success("CodeMap", None, &mut unreadable);
        finalize_tool_result(&mut unreadable);
        let structured = unreadable.structured_content.expect("structured CodeMap diagnostic");
        assert_eq!(structured["output"], diagnostic, "{structured}");

        let mut failure = tool_failure("CodeMap", &WinxError::BashStateNotInitialized, None)
            .expect("tool-level error");
        finalize_tool_result(&mut failure);
        let structured = failure.structured_content.expect("structured CodeMap error");
        assert_eq!(structured["output"], structured["message"], "{structured}");
    }

    #[test]
    fn finalize_redacts_text_and_mirror_identically() {
        let token = format!("ghp_{}", "a".repeat(40));
        let mut result =
            CallToolResult::success(vec![ContentBlock::text(format!("token={token} ok"))]);
        result.structured_content = Some(json!({
            "status": "completed",
            "tool": "BashCommand",
            "output": format!("token={token} ok"),
            "data": {"note": format!("saw {token}")}
        }));
        finalize_tool_result(&mut result);
        let text = result_text(&result);
        assert_eq!(text, "token=[REDACTED:github-token] ok");
        let structured = result.structured_content.expect("structured result");
        assert_eq!(structured["output"], text);
        assert_eq!(structured["data"]["note"], "saw [REDACTED:github-token]");
        assert!(!serde_json::to_string(&structured).expect("json").contains(&token));
    }

    #[test]
    fn mirror_is_never_less_redacted_than_the_text_blocks() {
        // Per-block redaction cannot see a key that straddles two blocks; the
        // joined mirror is redacted as a whole, so it must scrub it anyway.
        let mut result = CallToolResult::success(vec![
            ContentBlock::text("-----BEGIN PRIVATE KEY-----\nsecret-head"),
            ContentBlock::text("secret-tail\n-----END PRIVATE KEY-----"),
        ]);
        result.structured_content = Some(json!({"status": "completed", "tool": "BashCommand"}));
        finalize_tool_result(&mut result);
        let output = result.structured_content.expect("structured")["output"]
            .as_str()
            .expect("mirrored output")
            .to_string();
        assert!(!output.contains("secret-head"), "{output}");
        assert!(output.contains("[REDACTED:"), "{output}");
    }

    #[test]
    fn mirror_text_output_tracks_content_rewrites() {
        let mut result = CallToolResult::success(vec![ContentBlock::text("before")]);
        result.structured_content =
            Some(json!({"status": "completed", "tool": "ReadFiles", "output": "before"}));
        result.content = vec![ContentBlock::text("after"), ContentBlock::text("more")];
        mirror_text_output(&mut result);
        assert_eq!(
            result.structured_content.as_ref().expect("structured")["output"],
            "after\nmore"
        );

        result.content = vec![ContentBlock::image("AAAA", "image/png")];
        mirror_text_output(&mut result);
        assert!(result.structured_content.as_ref().expect("structured").get("output").is_none());

        let mut plain = CallToolResult::success(vec![ContentBlock::text("no envelope")]);
        mirror_text_output(&mut plain);
        assert!(plain.structured_content.is_none());
    }

    #[test]
    fn code_map_navigation_payload_is_not_duplicated_inside_data_result() {
        let navigation = json!({
            "mode": "repo",
            "files_shown": 1,
            "files": [{"file": "src/lib.rs", "symbols": []}],
            "truncated": false,
            "files_scanned": 1,
            "payload_bytes": 128
        });
        let mut result = CallToolResult::success(vec![ContentBlock::text("src/lib.rs\n")]);
        result.structured_content = Some(navigation);

        decorate_success("CodeMap", None, &mut result);

        let structured = result.structured_content.expect("structured CodeMap result");
        assert_eq!(structured["files"][0]["file"], "src/lib.rs");
        assert!(structured["data"].get("result").is_none(), "{structured}");
    }

    #[test]
    fn initialize_metadata_is_flattened_into_the_shared_data_envelope() {
        let mut result = CallToolResult::success(vec![ContentBlock::text("attached")]);
        result.structured_content = Some(json!({
            "initialize_transition": "attached_existing",
            "initialize_reused": true,
            "initialize_response_mode": "compact",
            "context_bytes": 0,
            "workspace_root": "/workspace"
        }));
        decorate_success(
            "Initialize",
            Some(&json!({"thread_id":"thread","mode_name":"wcgw"})),
            &mut result,
        );

        let structured = result.structured_content.expect("structured Initialize result");
        assert_eq!(structured["status"], "completed");
        assert_eq!(structured["data"]["initialize_transition"], "attached_existing");
        assert_eq!(structured["data"]["initialize_reused"], true);
        assert_eq!(structured["data"]["initialize_response_mode"], "compact");
        assert_eq!(structured["data"]["workspace_root"], "/workspace");
        assert!(structured["data"].get("result").is_none());
    }

    #[test]
    fn missing_session_recovery_supplies_an_exact_first_call() {
        let initialize = tool_failure(
            "Initialize",
            &WinxError::BashStateNotInitialized,
            Some(&json!({
                "type": "reset_shell",
                "any_workspace_path": "/workspace",
                "initial_files_to_read": ["README.md"],
                "mode_name": "code_writer",
                "thread_id": "thread",
                "code_writer_config": {"allowed_commands": ["cargo"], "allowed_globs": ["**/*.rs"]}
            })),
        )
        .expect("Initialize recovery result");
        let structured = initialize.structured_content.expect("structured Initialize recovery");
        let arguments = &structured["nextAction"]["arguments"];
        assert_eq!(structured["status"], "needs_initialize");
        assert_eq!(structured["errorCode"], "not_initialized");
        assert_eq!(arguments["type"], "first_call");
        assert_eq!(arguments["any_workspace_path"], "/workspace");
        assert_eq!(arguments["thread_id"], "thread");
        assert_eq!(arguments["mode_name"], "code_writer");
        assert_eq!(arguments["initial_files_to_read"], json!(["README.md"]));

        let stateful = tool_failure(
            "ReadFiles",
            &WinxError::BashStateNotInitialized,
            Some(&json!({
                "file_paths": ["/workspace/README.md"],
                "thread_id": "thread",
                "workspace_root": "/workspace"
            })),
        )
        .expect("stateful recovery result");
        let structured = stateful.structured_content.expect("structured stateful recovery");
        let arguments = &structured["nextAction"]["arguments"];
        assert_eq!(arguments["type"], "first_call");
        assert_eq!(arguments["any_workspace_path"], "/workspace");
        assert_eq!(arguments["thread_id"], "thread");
        assert_eq!(arguments["mode_name"], "wcgw");
    }

    #[test]
    fn unread_file_error_provides_exact_read_call() {
        let error = WinxError::FileReadRequired {
            path: "/workspace/README.md".into(),
            reason: crate::errors::ReadRequirement::InsufficientCoverage,
            ranges: vec!["20-40".into(), "90-".into()],
            message: "Read more of the file before overwriting. Unread line ranges: 20-40, 90-"
                .to_string(),
        };
        let result = tool_failure(
            "FileWriteOrEdit",
            &error,
            Some(&json!({
                "thread_id":"thread",
                "workspace_root":"/workspace",
                "file_path":"/workspace/README.md"
            })),
        )
        .expect("tool-level error");
        assert_eq!(result.is_error, Some(true));
        let structured = result.structured_content.expect("structured error");
        assert_eq!(structured["status"], "needs_read");
        assert_eq!(structured["retrySameCall"], false);
        assert_eq!(
            structured["nextAction"]["arguments"]["file_paths"],
            json!(["/workspace/README.md:20-40", "/workspace/README.md:90-"])
        );
        assert_eq!(structured["nextAction"]["arguments"]["workspace_root"], "/workspace");
    }

    #[test]
    fn temporary_artifact_policy_returns_a_correctable_structured_result() {
        let error = WinxError::TemporaryArtifactPolicy {
            path: "/workspace/.winx_tmp/carrier.py".into(),
            temporary_artifact_dir: "/workspace/.winx/tmp/session-deadbeefdeadbeef".into(),
            message: "use the managed session directory".to_string(),
        };
        let result = tool_failure(
            "FileWriteOrEdit",
            &error,
            Some(&json!({
                "thread_id":"thread",
                "workspace_root":"/workspace",
                "file_path":"/workspace/.winx_tmp/carrier.py"
            })),
        )
        .expect("tool result");

        assert_eq!(result.is_error, Some(true));
        let structured = result.structured_content.expect("structured policy result");
        assert_eq!(structured["status"], "invalid_input");
        assert_eq!(structured["errorCode"], "temporary_artifact_policy");
        assert_eq!(structured["retryable"], true);
        assert_eq!(structured["retrySameCall"], false);
        assert_eq!(
            structured["data"]["temporary_artifact_dir"],
            "/workspace/.winx/tmp/session-deadbeefdeadbeef"
        );
        assert_eq!(structured["nextAction"]["tool"], "FileWriteOrEdit");
    }

    #[test]
    fn post_bash_temp_overflow_preserves_execution_and_requires_cleanup() {
        let mut result = CallToolResult::success(vec![ContentBlock::text("command output")]);
        result.structured_content = Some(json!({
            "status": "completed",
            "tool": "BashCommand",
            "message": "BashCommand completed.",
            "retryable": false,
            "retrySameCall": false,
            "requiredReads": [],
            "data": {}
        }));
        let usage = crate::utils::agent_temp::TemporaryArtifactUsage {
            temporary_artifact_dir: "/workspace/.winx/tmp/session-deadbeefdeadbeef".into(),
            total_bytes: 129,
            max_total_bytes: 1_024,
            session_bytes: 129,
            max_session_bytes: 128,
            session_files: 129,
            max_session_files: 128,
            largest_file_bytes: 2,
            max_file_bytes: 64,
            stale_pruned_files: 0,
            stale_pruned_bytes: 0,
            over_budget: true,
        };

        attach_temporary_artifact_usage(
            &mut result,
            Some(&json!({"thread_id":"thread","workspace_root":"/workspace"})),
            &usage,
        );

        assert_ne!(result.is_error, Some(true));
        assert_eq!(result.content.len(), 2);
        let structured = result.structured_content.expect("structured Bash result");
        assert_eq!(structured["status"], "completed");
        assert_eq!(structured["data"]["temporary_artifact_cleanup_required"], true);
        assert_eq!(structured["data"]["temporary_artifact_budget"]["session_files"], 129);
        assert_eq!(structured["nextAction"]["tool"], "BashCommand");
        assert!(structured["nextAction"].get("arguments").is_none());
    }

    #[test]
    fn running_temp_overflow_supplies_a_concrete_interrupt_action() {
        let mut result = CallToolResult::success(vec![ContentBlock::text("still running")]);
        result.structured_content = Some(json!({
            "status": "running",
            "tool": "BashCommand",
            "message": "BashCommand is still running.",
            "retryable": false,
            "retrySameCall": false,
            "requiredReads": [],
            "data": {"bg_command_id": "bg-7"}
        }));
        let usage = crate::utils::agent_temp::TemporaryArtifactUsage {
            temporary_artifact_dir: "/workspace/.winx/tmp/session-deadbeefdeadbeef".into(),
            total_bytes: 129,
            max_total_bytes: 1_024,
            session_bytes: 129,
            max_session_bytes: 128,
            session_files: 129,
            max_session_files: 128,
            largest_file_bytes: 2,
            max_file_bytes: 64,
            stale_pruned_files: 0,
            stale_pruned_bytes: 0,
            over_budget: true,
        };

        attach_temporary_artifact_usage(
            &mut result,
            Some(&json!({"thread_id":"thread","workspace_root":"/workspace"})),
            &usage,
        );

        let structured = result.structured_content.expect("structured Bash result");
        let arguments = &structured["nextAction"]["arguments"];
        assert_eq!(structured["status"], "running");
        assert_eq!(arguments["action_json"]["type"], "send_specials");
        assert_eq!(arguments["action_json"]["send_specials"][0], "Ctrl-c");
        assert_eq!(arguments["action_json"]["bg_command_id"], "bg-7");
        assert_eq!(arguments["wait_policy"], "return_early");
        assert_eq!(arguments["thread_id"], "thread");
        assert_eq!(arguments["workspace_root"], "/workspace");
    }

    #[test]
    fn incompatible_wait_policy_returns_corrected_arguments() {
        let error = WinxError::InvalidWaitPolicyForAction {
            wait_policy: "until_complete".to_string(),
            action: "status_check".to_string(),
        };
        let result = tool_failure(
            "BashCommand",
            &error,
            Some(&json!({
                "thread_id":"thread",
                "workspace_root":"/workspace",
                "wait_policy":"until_complete",
                "action_json":{"type":"status_check","status_check":true}
            })),
        )
        .expect("recoverable tool result");

        assert_eq!(result.is_error, Some(true));
        let structured = result.structured_content.expect("structured wait-policy result");
        assert_eq!(structured["status"], "invalid_input");
        assert_eq!(structured["errorCode"], "wait_policy_incompatible_with_action");
        assert_eq!(structured["nextAction"]["arguments"]["wait_policy"], "return_early");
        assert_eq!(structured["data"]["action"], "status_check");
    }

    #[test]
    fn derived_code_map_budget_redirects_to_canonical_source_tools() {
        let error = WinxError::DerivedCodeMapBudget {
            path: "/workspace/.winx/tmp/session-deadbeefdeadbeef/carrier.py".into(),
            temporary_artifact_dir: "/workspace/.winx/tmp/session-deadbeefdeadbeef".into(),
            calls_used: 64,
            calls_limit: 64,
            unique_files_used: 24,
            unique_files_limit: 24,
            message: "budget exhausted".to_string(),
        };
        let result = tool_failure(
            "CodeMap",
            &error,
            Some(&json!({
                "operation": "outline",
                "path": "/workspace/.winx/tmp/session-deadbeefdeadbeef/carrier.py",
                "thread_id": "thread",
                "workspace_root": "/workspace"
            })),
        )
        .expect("tool-level budget result");

        assert_eq!(result.is_error, Some(true));
        let structured = result.structured_content.expect("structured budget error");
        assert_eq!(structured["status"], "invalid_input");
        assert_eq!(structured["errorCode"], "derived_code_map_budget_exhausted");
        assert_eq!(structured["retrySameCall"], false);
        assert_eq!(structured["nextAction"]["tool"], "ReadFiles");
        assert_eq!(structured["data"]["calls_used"], 64);
        assert_eq!(structured["data"]["unique_files_limit"], 24);
    }

    #[test]
    fn running_command_success_points_to_status_check() {
        let result = bash_success_result(
            Some(&json!({
                "thread_id":"thread",
                "workspace_root":"/workspace",
                "action_json":{"type":"command","command":"test"}
            })),
            BashCommandRuntimeResult {
                result: crate::tools::bash_command::BashCommandResult {
                    output: "build output with arbitrary text".to_string(),
                    state: BashCommandState {
                        process_status: crate::tools::bash_command::BashProcessStatus::Running,
                        background_id: None,
                        running_for_seconds: Some(1),
                        exit_code: None,
                        cwd: "/workspace".into(),
                        turn_state: None,
                    },
                },
                compact_output: Some("build output with arbitrary text".to_string()),
                command_generation: Some(1),
                execution_token: Some(crate::runtime::ShellExecutionToken {
                    guardian_epoch: "guardian".to_string(),
                    session_epoch: "session".to_string(),
                    generation: 1,
                }),
                generation_bound_actions: true,
                dropped_output_file: None,
                output_truncated: false,
            },
            false,
        )
        .expect("typed BashCommand result");
        let structured = result.structured_content.expect("structured success");
        assert_eq!(structured["status"], "running");
        assert_eq!(structured["nextAction"]["tool"], "BashCommand");
        assert_eq!(structured["nextAction"]["arguments"]["action_json"]["type"], "status_check");
        assert_eq!(structured["nextAction"]["arguments"]["workspace_root"], "/workspace");
        assert_eq!(structured["data"]["command_generation"], 1);
        assert_eq!(structured["data"]["execution_id"], "guardian:session:1");
    }

    #[test]
    fn workspace_mismatch_has_a_safe_structured_recovery() {
        let error = WinxError::WorkspaceBindingMismatch {
            thread_id: "wrong-thread".to_string(),
            requested_workspace: "/intended".into(),
            bound_workspace: "/other".into(),
        };
        let result = tool_failure(
            "BashCommand",
            &error,
            Some(&json!({
                "thread_id": "wrong-thread",
                "workspace_root": "/intended"
            })),
        )
        .expect("tool-level coherence error");

        assert_eq!(result.is_error, Some(true));
        let structured = result.structured_content.expect("structured coherence error");
        assert_eq!(structured["status"], "conflict");
        assert_eq!(structured["errorCode"], "workspace_binding_mismatch");
        assert_eq!(structured["retrySameCall"], false);
        assert_eq!(structured["data"]["bound_workspace"], "/other");
        assert_eq!(structured["nextAction"]["tool"], "Initialize");
        assert_eq!(structured["nextAction"]["arguments"]["any_workspace_path"], "/intended");
    }

    #[test]
    fn unified_search_conflict_points_to_line_patch_without_shell_fallback() {
        let error = WinxError::IndexedEditError {
            index: 1,
            path: "/workspace/src/lib.rs".into(),
            mode: "search_replace".to_string(),
            source: Box::new(WinxError::SearchBlockNotFound("stale block".to_string())),
        };
        let arguments = json!({
            "files": [{
                "file_path": "/workspace/src/lib.rs",
                "mode": "search_replace",
                "content": "stale block"
            }],
            "thread_id": "thread",
            "workspace_root": "/workspace"
        });
        let result =
            tool_failure("EditFiles", &error, Some(&arguments)).expect("tool-level edit conflict");

        assert_eq!(result.is_error, Some(true));
        let text = result_text(&result);
        assert!(text.contains("mode=line_patch"), "{text}");
        assert!(text.contains("Do not retry SEARCH"), "{text}");
        let structured = result.structured_content.expect("structured edit conflict");
        assert_eq!(structured["status"], "conflict");
        assert_eq!(structured["errorCode"], "search_block_not_found");
        assert_eq!(structured["nextAction"]["tool"], "ReadFiles");
        assert!(structured["nextAction"]["instruction"]
            .as_str()
            .is_some_and(|instruction| instruction.contains("mode=line_patch")));
        assert_eq!(structured["data"]["recommended_edit_mode"], "line_patch");
        assert_eq!(structured["data"]["ordinary_shell_edit_fallback"], false);
        assert_eq!(structured["data"]["edit_applied"], false);
    }

    #[test]
    fn repeated_initialize_for_another_workspace_is_terminal() {
        let error = WinxError::WorkspaceBindingMismatch {
            thread_id: "current-thread".to_string(),
            requested_workspace: "/external/target".into(),
            bound_workspace: "/current/project".into(),
        };
        let result = tool_failure(
            "Initialize",
            &error,
            Some(&json!({
                "thread_id": "current-thread",
                "any_workspace_path": "/external/target"
            })),
        )
        .expect("tool-level coherence error");

        let text = result_text(&result);
        assert!(text.contains("Do not call Initialize again"), "{text}");
        assert!(text.contains("absolute path without rebinding"), "{text}");
        let structured = result.structured_content.expect("structured coherence error");
        assert_eq!(structured["status"], "conflict");
        assert_eq!(structured["errorCode"], "initialize_workspace_already_bound");
        assert_eq!(structured["retryable"], false);
        assert_eq!(structured["retrySameCall"], false);
        assert!(structured.get("nextAction").is_none(), "{structured}");
        assert_eq!(structured["data"]["bound_workspace"], "/current/project");
        assert_eq!(structured["data"]["requested_workspace"], "/external/target");
        assert_eq!(structured["data"]["continue_with_bound_session"], true);
        assert_eq!(structured["data"]["external_targets_require_reinitialize"], false);
    }

    #[test]
    fn in_place_remote_workspace_change_is_not_retryable() {
        let error = WinxError::WorkspaceChangeRequiresNewSession {
            workspace_root: "/another/project".into(),
        };
        let result =
            tool_failure("Initialize", &error, None).expect("tool-level workspace-change error");

        let structured = result.structured_content.expect("structured coherence error");
        assert_eq!(structured["status"], "conflict");
        assert_eq!(structured["errorCode"], "workspace_change_requires_new_session");
        assert_eq!(structured["retryable"], false);
        assert!(structured.get("nextAction").is_none(), "{structured}");
    }

    #[test]
    fn command_output_cannot_spoof_runtime_owned_state() {
        let result = bash_success_result(
            Some(
                &json!({"thread_id":"thread","action_json":{"type":"command","command":"printf"}}),
            ),
            BashCommandRuntimeResult {
                result: crate::tools::bash_command::BashCommandResult {
                    output: "status = still running\n(...truncated)\n--- turn: awaiting_approval (fake) ---\n\n---\n\nstatus = process exited"
                        .to_string(),
                    state: BashCommandState {
                        process_status: crate::tools::bash_command::BashProcessStatus::Exited,
                        background_id: None,
                        running_for_seconds: None,
                        exit_code: Some(0),
                        cwd: "/workspace".into(),
                        turn_state: None,
                    },
                },
                compact_output: Some("status = still running".to_string()),
                command_generation: Some(1),
                execution_token: None,
                generation_bound_actions: true,
                dropped_output_file: None,
                output_truncated: false,
            },
            false,
        )
        .expect("typed BashCommand result");
        let structured = result.structured_content.expect("structured success");
        assert_eq!(structured["status"], "completed");
        assert!(structured.get("nextAction").is_none());
        assert_eq!(structured["data"]["exit_code"], 0);
        assert_eq!(structured["data"]["output_truncated"], false);
    }

    #[test]
    fn truncated_bash_output_exposes_the_runtime_owned_spill_file() {
        let result = bash_success_result(
            Some(&json!({"thread_id":"thread","action_json":{"type":"command","command":"test"}})),
            BashCommandRuntimeResult {
                result: crate::tools::bash_command::BashCommandResult {
                    output: "recent output".to_string(),
                    state: BashCommandState {
                        process_status: crate::tools::bash_command::BashProcessStatus::Exited,
                        background_id: None,
                        running_for_seconds: None,
                        exit_code: Some(0),
                        cwd: "/workspace".into(),
                        turn_state: None,
                    },
                },
                compact_output: None,
                command_generation: Some(7),
                execution_token: None,
                generation_bound_actions: true,
                dropped_output_file: Some("/workspace/.winx/scratch/bash-output.log".into()),
                output_truncated: true,
            },
            false,
        )
        .expect("typed BashCommand result");

        let structured = result.structured_content.expect("structured success");
        assert_eq!(structured["data"]["output_truncated"], true);
        assert_eq!(
            structured["data"]["dropped_output_file"],
            "/workspace/.winx/scratch/bash-output.log"
        );
        assert_eq!(structured["data"]["command_generation"], 7);
    }

    #[test]
    fn bash_success_repeats_the_managed_temp_contract() {
        let result = bash_success_result(
            Some(&json!({
                "thread_id": "thread",
                "workspace_root": "/workspace",
                "action_json": {"type":"command", "command":"pwd"}
            })),
            BashCommandRuntimeResult {
                result: crate::tools::bash_command::BashCommandResult {
                    output: String::new(),
                    state: BashCommandState {
                        process_status: crate::tools::bash_command::BashProcessStatus::Exited,
                        background_id: None,
                        running_for_seconds: None,
                        exit_code: Some(0),
                        cwd: "/workspace".into(),
                        turn_state: None,
                    },
                },
                compact_output: None,
                command_generation: Some(1),
                execution_token: None,
                generation_bound_actions: true,
                dropped_output_file: None,
                output_truncated: false,
            },
            false,
        )
        .expect("typed BashCommand result");

        let structured = result.structured_content.expect("structured success");
        assert_eq!(structured["data"]["temporary_artifact_env"], "WINX_TEMP_DIR");
        assert!(
            structured["data"]["temporary_artifact_dir"].as_str().is_some_and(|path| {
                path.replace('\\', "/").starts_with("/workspace/.winx/tmp/session-")
            }),
            "{structured}"
        );
    }

    fn exited_verification(exit_code: i32) -> CallToolResult {
        bash_success_result(
            Some(&json!({"thread_id":"thread","action_json":{"type":"command"}})),
            BashCommandRuntimeResult {
                result: crate::tools::bash_command::BashCommandResult {
                    output: format!("verification output {exit_code}"),
                    state: BashCommandState {
                        process_status: crate::tools::bash_command::BashProcessStatus::Exited,
                        background_id: None,
                        running_for_seconds: None,
                        exit_code: Some(exit_code),
                        cwd: "/workspace".into(),
                        turn_state: None,
                    },
                },
                compact_output: None,
                command_generation: Some(1),
                execution_token: None,
                generation_bound_actions: true,
                dropped_output_file: None,
                output_truncated: false,
            },
            false,
        )
        .expect("typed verification result")
    }

    fn verification_recovery() -> VerificationRecovery {
        VerificationRecovery {
            id: "verify_receipt".to_string(),
            tool: "VerifyEdit",
            arguments: json!({
                "verification_id": "verify_receipt",
                "command": "cargo test",
                "thread_id": "thread",
                "workspace_root": "/workspace"
            }),
        }
    }

    #[test]
    fn edit_verification_surfaces_success_without_losing_edit_metadata() {
        let arguments = json!({"thread_id":"thread","file_path":"/workspace/lib.rs"});
        let mut result = edit_verification_result(
            "FileWriteOrEdit",
            Some(&arguments),
            "Successfully edited /workspace/lib.rs",
            exited_verification(0),
            &verification_recovery(),
        );
        decorate_success("FileWriteOrEdit", Some(&arguments), &mut result);

        assert_ne!(result.is_error, Some(true));
        let structured = result.structured_content.expect("structured verification");
        assert_eq!(structured["status"], "completed");
        assert_eq!(structured["data"]["edit_applied"], true);
        assert_eq!(structured["data"]["verification_exit_code"], 0);
        assert!(
            structured["data"].get("file_path").is_none(),
            "edit paths are attached later from PreparedEditContext, never raw wire arguments"
        );
    }

    #[test]
    fn failed_edit_verification_is_completed_with_issues_and_never_retries_the_edit() {
        let result = edit_verification_result(
            "MultiFileEdit",
            Some(&json!({"thread_id":"thread","files":[]})),
            "MultiFileEdit applied all edits",
            exited_verification(7),
            &verification_recovery(),
        );

        assert_ne!(result.is_error, Some(true));
        let text = result.content[0].as_text().expect("text result");
        assert!(text.text.starts_with("EDIT APPLIED."));
        assert!(text.text.contains("do not repeat the original edit"));
        let structured = result.structured_content.expect("structured verification");
        assert_eq!(structured["status"], "completed_with_issues");
        assert_eq!(structured["errorCode"], "verification_failed");
        assert_eq!(structured["retryable"], false);
        assert_eq!(structured["retrySameCall"], false);
        assert_eq!(structured["nextAction"]["tool"], "VerifyEdit");
        assert_eq!(structured["nextAction"]["arguments"]["verification_id"], "verify_receipt");
        assert_eq!(structured["data"]["edit_applied"], true);
        assert_eq!(structured["data"]["original_edit_retryable"], false);
        assert_eq!(structured["data"]["follow_up_required"], true);
        assert_eq!(structured["data"]["verification_status"], "failed");
        assert_eq!(structured["data"]["verification_passed"], false);
        assert_eq!(structured["data"]["verification_exit_code"], 7);
    }

    #[test]
    fn standalone_verification_failure_is_retryable_only_after_correction() {
        let arguments = json!({
            "verification_id": "verify_receipt",
            "command": "cargo test",
            "thread_id": "thread",
            "workspace_root": "/workspace"
        });
        let result = verify_edit_result(Some(&arguments), "verify_receipt", exited_verification(2));

        assert_eq!(result.is_error, Some(true));
        let structured = result.structured_content.expect("structured verification");
        assert_eq!(structured["status"], "failed");
        assert_eq!(structured["errorCode"], "verification_failed");
        assert_eq!(structured["retryable"], true);
        assert_eq!(structured["retrySameCall"], false);
        assert_eq!(structured["nextAction"]["tool"], "VerifyEdit");
        assert_eq!(structured["nextAction"]["arguments"], arguments);
        assert_eq!(structured["data"]["original_edit_retryable"], false);
    }

    #[test]
    fn active_legacy_verification_keeps_exact_verify_edit_recovery_surface() {
        let arguments = json!({
            "verification_id": "verify_legacy",
            "command": "cargo test",
            "wait_for_seconds": 15.0,
            "thread_id": "thread",
            "workspace_root": "/workspace"
        });
        let mut nested = CallToolResult::success(vec![ContentBlock::text("still running")]);
        nested.structured_content = Some(json!({
            "status": "running",
            "tool": "BashCommand",
            "retryAfterMs": 1000,
            "nextAction": {
                "tool": "BashCommand",
                "arguments": {
                    "action_json": {
                        "type": "verify",
                        "verification_id": "verify_canonical",
                        "command": "cargo test"
                    }
                }
            },
            "data": {}
        }));
        let result = verify_edit_result(Some(&arguments), "verify_legacy", nested);
        let structured = result.structured_content.expect("structured verification");
        assert_eq!(structured["status"], "running");
        assert_eq!(structured["nextAction"]["tool"], "VerifyEdit");
        assert_eq!(structured["nextAction"]["arguments"], arguments);
        assert!(!structured["nextAction"].to_string().contains("verify_canonical"));
    }

    #[test]
    fn active_initial_legacy_edit_keeps_verify_edit_recovery_surface() {
        let edit_arguments = json!({
            "file_path": "/workspace/file.rs",
            "thread_id": "thread",
            "workspace_root": "/workspace"
        });
        let verify_arguments = json!({
            "verification_id": "verify_legacy",
            "command": "cargo test",
            "wait_for_seconds": 15.0,
            "thread_id": "thread",
            "workspace_root": "/workspace"
        });
        for tool in ["FileWriteOrEdit", "MultiFileEdit"] {
            let mut nested = CallToolResult::success(vec![ContentBlock::text("still running")]);
            nested.structured_content = Some(json!({
                "status": "running",
                "tool": "BashCommand",
                "retryAfterMs": 1000,
                "nextAction": {
                    "tool": "BashCommand",
                    "arguments": {"action_json": {"type": "status_check"}}
                },
                "data": {}
            }));

            let result = edit_verification_result(
                tool,
                Some(&edit_arguments),
                "edit committed",
                nested,
                &VerificationRecovery {
                    id: "verify_legacy".to_string(),
                    tool: "VerifyEdit",
                    arguments: verify_arguments.clone(),
                },
            );
            let structured = result.structured_content.expect("structured verification");
            assert_eq!(structured["status"], "running");
            assert_eq!(structured["nextAction"]["tool"], "VerifyEdit");
            assert_eq!(structured["nextAction"]["arguments"], verify_arguments);
        }
    }

    #[test]
    fn nested_edit_errors_keep_syntax_and_temp_policy_classification() {
        let syntax = WinxError::IndexedEditError {
            index: 1,
            path: "/workspace/file.rs".into(),
            mode: "search_replace".to_string(),
            source: Box::new(WinxError::SearchReplaceSyntaxError("bad markers".to_string())),
        };
        let syntax_result = tool_failure("EditFiles", &syntax, None).expect("syntax result");
        assert_eq!(
            syntax_result.structured_content.as_ref().expect("structured")["errorCode"],
            "invalid_tool_input"
        );

        let temporary = WinxError::EditContextError {
            path: "/workspace/.winx_tmp/helper.rs".into(),
            source: Box::new(WinxError::TemporaryArtifactPolicy {
                path: "/workspace/.winx_tmp/helper.rs".into(),
                temporary_artifact_dir: "/workspace/.winx/tmp/session-id".into(),
                message: "managed path required".to_string(),
            }),
        };
        let temporary_result =
            tool_failure("FileWriteOrEdit", &temporary, None).expect("temp policy result");
        assert_eq!(
            temporary_result.structured_content.as_ref().expect("structured")["errorCode"],
            "temporary_artifact_policy"
        );
    }

    #[test]
    fn effective_policy_removes_unadvertised_read_recovery() {
        let error = WinxError::FileReadRequired {
            path: "/workspace/file.rs".into(),
            reason: crate::errors::ReadRequirement::NeverRead,
            ranges: Vec::new(),
            message: "fresh read required".to_string(),
        };
        let mut result = tool_failure(
            "FileWriteOrEdit",
            &error,
            Some(&json!({"thread_id":"thread","workspace_root":"/workspace"})),
        )
        .expect("recovery result");
        let policy = crate::tool_policy::ToolPolicy::from_allowed_tools(["FileWriteOrEdit"])
            .expect("custom policy");
        enforce_next_action_policy(&mut result, policy);

        let text = result_text(&result);
        let structured = result.structured_content.expect("structured result");
        assert_eq!(structured["status"], "denied");
        assert_eq!(structured["errorCode"], "policy_blocked");
        assert!(structured.get("nextAction").is_none());
        assert_eq!(structured["requiredReads"], json!([]));
        assert!(text.starts_with("POLICY BLOCKED."), "{text}");
        assert_eq!(structured["output"], text, "policy banner must be mirrored");
    }

    #[test]
    fn effective_policy_blocks_hidden_verification_without_hiding_committed_edit() {
        let mut result = edit_verification_result(
            "FileWriteOrEdit",
            Some(&json!({"thread_id":"thread","workspace_root":"/workspace"})),
            "edit committed",
            exited_verification(1),
            &verification_recovery(),
        );
        let policy =
            crate::tool_policy::ToolPolicy::from_allowed_tools(["FileWriteOrEdit", "BashCommand"])
                .expect("custom policy");
        enforce_next_action_policy(&mut result, policy);

        assert_ne!(result.is_error, Some(true));
        let structured = result.structured_content.expect("structured result");
        assert_eq!(structured["status"], "completed_with_issues");
        assert_eq!(structured["errorCode"], "policy_blocked");
        assert_eq!(structured["data"]["edit_applied"], true);
        assert!(structured.get("nextAction").is_none());
    }

    #[test]
    fn compact_negotiation_falls_back_to_legacy_runtime_output() {
        let legacy = "child output\n\n---\n\nstatus = process exited\ncwd = /workspace";
        let result = bash_success_result(
            Some(&json!({"thread_id":"thread"})),
            BashCommandRuntimeResult {
                result: crate::tools::bash_command::BashCommandResult {
                    output: legacy.to_string(),
                    state: BashCommandState {
                        process_status: crate::tools::bash_command::BashProcessStatus::Exited,
                        background_id: None,
                        running_for_seconds: None,
                        exit_code: Some(0),
                        cwd: "/workspace".into(),
                        turn_state: None,
                    },
                },
                compact_output: None,
                command_generation: None,
                execution_token: None,
                generation_bound_actions: false,
                dropped_output_file: None,
                output_truncated: false,
            },
            true,
        )
        .expect("legacy guardian result");
        let text = result.content[0].as_text().expect("text output");
        assert_eq!(text.text, legacy);
        assert!(result
            .structured_content
            .as_ref()
            .and_then(|value| value.get("data"))
            .and_then(|value| value.get("output_format"))
            .is_none());
    }
}