blyte-agent 0.71.0

The blyte agent loop: tools, context, persistent shell sessions, search and the command sandbox.
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
//! The turn loop, and the gate the worker cannot call.
//!
//! # Where the gate sits, and why it is not a tool
//!
//! Invariant II: an LLM must never grade its own homework. A gate the model can invoke is a
//! gate it can decline to invoke, or invoke selectively, or report the result of. So the gate
//! is not in the tool surface at all -- the runtime runs it when the model stops calling tools,
//! and the model learns the verdict the same way it learns anything else: as an observation it
//! did not choose.
//!
//! This is the piece blyte asserted as doctrine for months while the code let a
//! worker-authored test become the gate.
//!
//! # Why a failed gate resets the tree
//!
//! Invariant III. A failing attempt's edits must not accumulate across retries; the worker
//! begins each attempt from a verified checkpoint, carrying the failure telemetry rather than a
//! corrupted workspace. Measured independently at 3/3 against 2/3 and 25.3% fewer tokens per
//! solve (EXP-059). Rollback is on by default and switchable, because it is not free -- one run
//! reset a worker's committed feature five times (FINDINGS 13.2).

use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::time::Duration;

use blyte_provider::{Message, Provider, ProviderError, Request, StreamTiming, Usage, UserPart};

use crate::claim_check;
use crate::context::ContextStrategy;
use crate::fs::Fs;
use crate::gate_slots;
use crate::quote_expand;
use crate::research_check;
use crate::shell::Shell;
use crate::state::State;
use crate::tools;

/// How a run ended.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    /// The verification command exited 0. The only way to succeed.
    Verified,
    /// The task completed without a verification gate (e.g. conversation model task).
    Finished,
    /// Budget spent without the gate passing.
    BudgetExhausted,
    /// The model stopped calling tools and the gate kept failing.
    GateFailed,
    /// The check already fails at the base commit, so the task cannot pass until that is fixed.
    Blocked(String),
    /// The provider or environment broke. Distinct from failing work.
    Error(String),
}

#[derive(Debug, Clone)]
pub struct Budget {
    pub max_turns: u32,
    pub max_gate_attempts: u32,
    /// Wall-clock limit, checked before each turn. The harness stops itself and reports, rather
    /// than being killed from outside with its telemetry lost (FINDINGS 13.5).
    pub max_duration: Option<Duration>,
}

impl Default for Budget {
    fn default() -> Self {
        Self {
            max_turns: 60,
            max_gate_attempts: 5,
            max_duration: None,
        }
    }
}

/// One call of the main loop: what it cost, and how its prompt related to the previous call's.
/// `appended` means the prompt was the previous one plus `new_chars` of new messages, the only
/// case where a prefix cache can serve everything but the new part. Fresh input far above
/// `new_chars / 4` on an appended call is a cache miss; on a rewritten one (a fold) it is expected.
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct TurnUsage {
    pub turn: u32,
    pub input: u64,
    pub cached: u64,
    pub output: u64,
    pub thinking: u64,
    pub prompt_messages: usize,
    pub appended: bool,
    pub new_chars: usize,
    /// The fold budget in force for this call, for strategies that fold.
    #[serde(default)]
    pub fold_budget: Option<usize>,
    /// Wall time of this turn's model call, including any provider retries and their waits.
    #[serde(default)]
    pub model_ms: u64,
    /// Wall time spent executing this turn's tool calls (0 for a turn with none).
    #[serde(default)]
    pub tools_ms: u64,
    /// Milliseconds to the first data of the model call that ended this turn's calling
    /// (`None`: the provider does not stream, or no data arrived).
    #[serde(default)]
    pub first_data_ms: Option<u64>,
    /// Longest silence, in milliseconds, in that same call (0 when the provider does not stream).
    #[serde(default)]
    pub max_gap_ms: u64,
    /// One entry per attempt of this turn's model call that failed and was retried, in order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub failed_attempts: Vec<FailedAttempt>,
}

/// A model call attempt that failed and was retried.
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct FailedAttempt {
    /// Wall time of the attempt, in milliseconds.
    pub elapsed_ms: u64,
    /// Whether the error was a timeout (`ProviderError::is_timeout`).
    pub timed_out: bool,
    /// As in [`blyte_provider::StreamTiming`]; `None` and 0 when the provider reported none.
    pub first_data_ms: Option<u64>,
    pub max_gap_ms: u64,
}

/// Characters a message contributes to a prompt, as the context strategies size them.
fn message_chars(m: &Message) -> usize {
    match m {
        Message::User(t) | Message::Assistant(t) => t.len(),
        Message::UserParts(parts) => parts
            .iter()
            .map(|p| match p {
                UserPart::Text(t) => t.len(),
                UserPart::Image { .. } => crate::context::IMAGE_TOKEN_ESTIMATE * 4,
            })
            .sum(),
        Message::ToolCall { arguments, .. } => arguments.to_string().len(),
        Message::ToolResult { content, .. } => content.len(),
    }
}

#[derive(Debug, Clone, Default)]
pub struct RunReport {
    pub outcome_turns: u32,
    pub usage: Usage,
    /// Turns whose response contained neither text nor a tool call -- pure waste, tracked
    /// because 47.6% of a previous harness's tokens went to turns that only waited (13.29).
    pub empty_turns: u32,
    /// Turns whose reply hit the output token limit and was cut off.
    pub truncated_turns: u32,
    /// Whether the run stopped because it kept repeating read/grep/glob calls without changing the workspace.
    pub read_loop: bool,
    /// Most repeated read/grep/glob calls seen between two workspace changes (the read-loop count).
    pub peak_read_repeats: u32,
    /// Whether the run stopped because consecutive turns kept folding the previous turn's results.
    pub fold_thrash: bool,
    /// Run stopped because a fix run made no change and kept calling tools after the last call.
    pub stalled: bool,
    /// Turns whose tool output exceeded half of the fold budget.
    pub big_read_turns: u32,
    pub tool_calls: u32,
    pub gate_attempts: u32,
    /// Transient provider failures (rate limits, overload) waited out during the run.
    pub provider_retries: u32,
    /// One entry per main-loop model call, in order.
    pub turn_usage: Vec<TurnUsage>,
    /// Wall time of each gate attempt, in order.
    pub gate_ms: Vec<u64>,
    /// The turn on which each gate attempt ran, in order (one entry per gate attempt).
    pub gate_turns: Vec<u32>,
    /// Time spent waiting for a gate slot on each attempt, in order (0 when acquired at once).
    pub gate_wait_ms: Vec<u64>,
    /// Gate output for each failed attempt, bounded to 4,000 characters (keeps the head and the tail).
    pub gate_failures: Vec<String>,
    /// Calls per tool name.
    pub tool_counts: BTreeMap<String, u32>,
    /// Whether the run stopped because spending reached `--max-cost`.
    pub cost_capped: bool,
    /// The model's last non-empty text response (trimmed).
    pub final_message: Option<String>,
    /// Problems with `report.md`'s quotes (`None` when the check did not run, `Some(vec![])` when it passed).
    pub quote_problems: Option<Vec<String>>,
    /// Model check of `report.md`'s claims against their cited lines (`None` when the check did not run).
    pub claim_check: Option<claim_check::ClaimCheck>,
    /// Reason the claim check did not run or stopped early (for example, out of time).
    pub claim_check_skipped: Option<String>,
    /// Elapsed seconds for the base check when it ran to completion.
    pub base_check_seconds: Option<f64>,
    /// Outcome of the base check when it ran to completion (`Some(true)` if passed, `Some(false)` if failed).
    pub base_check_passed: Option<bool>,
}

/// What happened on one turn, emitted as it happens.
///
/// A harness whose selling point is observability printed nothing until the run finished, so a
/// working run and one stuck on `find /` looked identical for three and a half minutes. Progress
/// is reported as it occurs, not summarised at the end.
#[derive(Debug, Clone)]
pub enum Event<'e> {
    /// Emitted when a streaming model call produced its first output delta (text, thinking, or tool call).
    FirstOutput {
        at: std::time::Instant,
    },
    Turn {
        n: u32,
        text: &'e str,
        usage: Usage,
    },
    /// Emitted immediately before a tool call executes, with the same abbreviated `input` as `Tool`.
    ToolStart {
        name: &'e str,
        input: String,
    },
    /// `input` is the call's arguments, abbreviated. Logging only the RESULT made a run
    /// undiagnosable: twenty bash calls that changed nothing, with no record of what was run.
    Tool {
        name: &'e str,
        input: String,
        summary: String,
        is_error: bool,
    },
    /// Emitted before sleeping to retry a transient model call error.
    Retry {
        attempt: u32,
        max: u32,
        wait_ms: u64,
        reason: String,
    },
    /// A gate attempt is starting (the check runs next). Emitted so a watcher can tell a run
    /// that is waiting on its gate from one that is thinking (`blyte dashboard`, 2026-09-30).
    GateStart {
        attempt: u32,
    },
    /// A gate waited for a machine-wide slot before running.
    GateSlotWait {
        ms: u64,
    },
    Gate {
        attempt: u32,
        passed: bool,
        output: &'e str,
    },
    RolledBack {
        to: &'e str,
    },
}

/// Retries allowed for one model call before a transient failure ends the run.
pub const MAX_PROVIDER_RETRIES: u32 = 6;

pub const PEER_MESSAGE_PREFIX: &str = "[blyte] Message from surface ";

pub const CONVERSATION_FIXED: &str = "\
Change nothing outside the repository yourself (blyte's own files under `.wt/` and its records are fine).\n\n\
## Working efficiently\n\
Independent reads, searches and commands can be issued as several tool calls in one \
turn: they run in order and you see every result together. Batch them whenever one \
does not depend on another's result; every turn you save is a full model call.\n";

/// Turns a fix run may spend without changing a file or running the gate before getting a nudge.
pub const NO_PROGRESS_TURNS: u32 = 20;
/// Minimum turns before the time-based no-progress nudge may fire.
pub const NO_PROGRESS_MIN_TURNS: u32 = 8;
/// Fraction of `max_duration` after which the no-progress nudge may fire (past `NO_PROGRESS_MIN_TURNS`).
pub const NO_PROGRESS_TIME_FRACTION: f64 = 0.25;
/// Turns after the no-progress nudge before the last call is sent.
pub const LAST_CALL_TURNS: u32 = 10;
/// Fraction of `max_duration` after which the last call may fire (once nudged).
pub const LAST_CALL_TIME_FRACTION: f64 = 0.5;

/// Turn on which a research run reminds the model to start `report.md` if it is still missing or empty.
pub const RESEARCH_FIRST_REPORT_TURN: u32 = 8;
/// Repeated read/grep/glob calls without a workspace change in a research run before warning.
pub const READ_LOOP_WARN: u32 = 20;
/// Repeated read/grep/glob calls without a workspace change allowed before ending the run.
const READ_LOOP_LIMIT: u32 = 30;
/// Extra turns a research run gets after reaching `READ_LOOP_LIMIT` to write `report.md` and stop.
pub const READ_LOOP_GRACE_TURNS: u32 = 3;

/// Most time a research run's main loop leaves for the claim check.
pub const CLAIM_CHECK_RESERVE_MAX: Duration = Duration::from_secs(180);

/// Time the main loop of a research run leaves before its deadline for the claim check:
/// a tenth of the time budget, at most `CLAIM_CHECK_RESERVE_MAX`.
pub fn claim_check_reserve(max_duration: Duration) -> Duration {
    (max_duration / 10).min(CLAIM_CHECK_RESERVE_MAX)
}

fn truncated(reason: Option<&str>) -> bool {
    matches!(
        reason,
        Some("MAX_TOKENS" | "CONTINUATION" | "max_tokens" | "length" | "incomplete")
    )
}

fn parse_resets_in_seconds(body: &str) -> Option<u64> {
    let key = "\"resets_in_seconds\"";
    let pos = body.find(key)?;
    let rest = body[pos + key.len()..].trim_start();
    let after_colon = rest.strip_prefix(':')?.trim_start();
    let digits: String = after_colon
        .chars()
        .take_while(|c| c.is_ascii_digit())
        .collect();
    if digits.is_empty() {
        return None;
    }
    digits.parse().ok()
}

/// Identifies provider errors caused by an exhausted usage quota (as opposed to a transient
/// burst rate limit). Returns `Some(message)` describing the exhaustion and reset duration if known.
pub fn quota_exhausted(e: &ProviderError) -> Option<String> {
    let ProviderError::Api { status: 429, body } = e else {
        return None;
    };
    let resets_in_seconds = parse_resets_in_seconds(body);
    let is_quota = body.contains("usage_limit_reached")
        || body.contains("insufficient_quota")
        || body.contains("PerDay")
        || resets_in_seconds.is_some_and(|s| s > 300);

    if !is_quota {
        return None;
    }

    let mut msg = "usage quota exhausted; not retrying".to_string();
    if let Some(secs) = resets_in_seconds {
        let human = if secs >= 86400 {
            format!("{}d {}h", secs / 86400, (secs % 86400) / 3600)
        } else if secs >= 3600 {
            format!("{}h {}m", secs / 3600, (secs % 3600) / 60)
        } else {
            format!("{}m", secs / 60)
        };
        msg.push_str(&format!(" (resets in {human})"));
    }
    Some(msg)
}

/// Transient provider failures worth waiting out: rate limits, overload, server errors and
/// dropped connections. Anything else (a malformed request, a bad key) fails the run at once.
pub fn is_transient(e: &ProviderError) -> bool {
    if quota_exhausted(e).is_some() {
        return false;
    }
    match e {
        ProviderError::Api { status, .. } => matches!(status, 429 | 500 | 502 | 503 | 504),
        ProviderError::Transport(_) | ProviderError::NoAnswer { .. } => true,
        _ => false,
    }
}

fn max_retries_for(e: &ProviderError) -> u32 {
    match e {
        ProviderError::NoAnswer { .. } => 1,
        _ => MAX_PROVIDER_RETRIES,
    }
}

/// Wait before retry `attempt` (1-based): 2, 4, 8, 16, 32, then 60 seconds.
pub fn retry_delay(attempt: u32) -> Duration {
    if let Ok(ms) = std::env::var("BLYTE_RETRY_DELAY_MS") {
        if let Ok(ms) = ms.trim().parse::<u64>() {
            return Duration::from_millis(ms);
        }
    }
    let exp = attempt.saturating_sub(1).min(5);
    Duration::from_secs((2u64 << exp).min(60))
}

/// How long the server asked us to wait, if it said: Gemini puts `"retryDelay": "37s"` in a
/// 429's body. Capped at 120 seconds.
pub fn server_retry_hint(e: &ProviderError) -> Option<Duration> {
    let ProviderError::Api { body, .. } = e else {
        return None;
    };
    let key = "\"retryDelay\"";
    let rest = &body[body.find(key)? + key.len()..];
    let value = &rest[rest.find('"')? + 1..];
    let secs: f64 = value[..value.find('s')?].trim().parse().ok()?;
    Some(Duration::from_secs_f64(secs.max(0.0)).min(Duration::from_secs(120)))
}

/// Wait before retry `attempt` (1-based): the backoff, or the server's hint when it is longer.
pub fn retry_wait(e: &ProviderError, attempt: u32) -> Duration {
    let backoff = retry_delay(attempt);
    server_retry_hint(e).map_or(backoff, |hint| hint.max(backoff))
}

/// State of a base check running beside the model's turns.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BaseCheckState {
    Pending,
    Passed,
    Failed { steps: Vec<String>, tail: String },
}

/// Handle to a background base check polled by [`Runner`].
pub trait BaseCheckHandle: Sync {
    fn poll(&self) -> BaseCheckState;
    fn wait(&self) -> BaseCheckState;
    fn stop(&self) {}
    fn elapsed_seconds(&self) -> Option<f64> {
        None
    }
}

/// How [`Runner`] checks the untouched base tree against the verification gate.
#[derive(Default)]
pub enum BaseCheck<'a> {
    #[default]
    None,
    BeforeFirstTurn,
    Polled(&'a dyn BaseCheckHandle),
}

/// Last 20 lines of gate output, formatted for base-check failure reports.
pub fn base_check_tail(output: &str) -> String {
    let lines: Vec<&str> = output.lines().collect();
    if lines.len() > 20 {
        lines[lines.len() - 20..].join("\n")
    } else {
        lines.join("\n")
    }
}

/// Convert a [`GateRunResult`] into a [`BaseCheckState`].
pub fn base_check_state_from_gate(result: &GateRunResult) -> BaseCheckState {
    if result.passed {
        BaseCheckState::Passed
    } else {
        BaseCheckState::Failed {
            steps: result.failures.iter().map(|f| f.step.clone()).collect(),
            tail: base_check_tail(&result.output),
        }
    }
}

fn base_check_blocked_message(failing_steps: &[String], tail: &str) -> String {
    let steps = failing_steps.join("; ");
    format!(
        "the check fails before any change ({steps}): {tail}. Fix the environment or the base commit, or pass --no-base-check if this task is meant to fix that check."
    )
}

pub struct Runner<'a> {
    pub provider: &'a dyn Provider,
    pub shell: &'a dyn Shell,
    pub fs: &'a dyn Fs,
    pub context: &'a dyn ContextStrategy,
    pub root: PathBuf,
    pub budget: Budget,
    /// Reset the tree to the checkpoint when the gate fails. Invariant III; default on.
    pub rollback: bool,
    /// Called as the run proceeds. Default is silent.
    pub on_event: Option<&'a dyn Fn(Event<'_>)>,
    /// Research run: periodically remind the model to keep report.md updated.
    pub research: bool,
    /// Research runs: check report.md's claims with the run's model (`claim_check`).
    pub claim_check: bool,
    /// How to check the verification gate against the untouched base tree.
    pub base_check: BaseCheck<'a>,
}

const CLAIM_PHRASES: &[&str] = &[
    "not caused by",
    "pre-existing",
    "preexisting",
    "already fail",
    "unrelated to",
    "fails on main",
    "fails on the base",
    "was failing before",
];

fn sh_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', r"'\''"))
}

impl<'a> Runner<'a> {
    fn emit(&self, e: Event<'_>) {
        if let Some(f) = self.on_event {
            f(e)
        }
    }
}

impl<'a> Runner<'a> {
    /// The immutable part of the prompt: who the worker is, what it may touch, where it runs.
    ///
    /// Held constant for the whole run so it caches.
    fn system_prompt(&self, state: &State, goal: Option<&str>) -> Result<String, String> {
        let bins = tools::available_binaries(self.shell, &self.root)?.join(", ");
        let where_ = self.shell.describe();

        if let Some(text) = &state.brief.instructions {
            let request_section = match goal {
                Some(goal) => format!("## Your user's first request\n{goal}\n\n"),
                None => String::new(),
            };
            return Ok(format!(
                "{text}{request_section}\
                 ## Environment\n{where_}\nAvailable: {bins}\n\n\
                 {CONVERSATION_FIXED}",
            ));
        }

        let rules = crate::rules::prompt_section(&self.root);

        let steps = gate_steps(&state.brief.verification_cmd);
        // Ungated runs have no check command, so the model must verify the work itself before stopping.
        let completion = if steps.is_empty() {
            "No command checks your work. When you stop, the result is judged by tests you \
             cannot see, so verify it yourself first: run the project's existing test suite and \
             the tests that cover your change, and check the edge cases the task describes. \
             If you searched for problems (with grep or other commands), run those same searches \
             again before you stop and confirm they find nothing left to fix. Stop \
             only when you are confident the task is complete."
                .to_string()
        } else {
            let verify = steps.join(" && ");
            format!(
                "Your work is accepted when `{verify}` exits 0. That command is run for you when \
                 you stop calling tools, and you do not decide the verdict. A failure costs a full \
                 rerun after your fix, so before you stop, run its quick parts yourself \
                 (formatting, lint) together with the tests that cover your change; leave the slow \
                 full run to it. Do not claim to be finished; simply stop when you believe the \
                 command will pass, and you will be told."
            )
        };
        Ok(format!(
            "You are a software engineer working in a repository.\n\n\
             ## Goal\n{goal}\n\n\
             ## How completion is decided\n\
             {completion}\n\n\
             ## Environment\n{where_}\nAvailable: {bins}\n\n\
             Change nothing outside the repository: no caches, other repositories, \
             home-directory files or system settings. If something outside it blocks you \
             (disk space, network, a missing tool), say so and stop.\n\n\
             {rules}\
             ## Working efficiently\n\
             Independent reads, searches and commands can be issued as several tool calls in one \
             turn: they run in order and you see every result together. Batch them whenever one \
             does not depend on another's result; every turn you save is a full model call.\n",
            goal = goal.unwrap_or(&state.brief.goal),
            completion = completion,
            where_ = where_,
            bins = bins,
            rules = rules,
        ))
    }

    /// Run the verification command. Runtime-only: nothing in the tool surface reaches this.
    ///
    /// A gate of several lines is several steps. On the first attempt, every step runs and all
    /// failures come back in one message. On retries, previously failing steps run first, and if
    /// any of them still fails, the attempt stops without re-running the passing steps.
    fn run_gate(
        &self,
        state: &State,
        last_failed: &[String],
        deadline: &mut Option<std::time::Instant>,
        now: &(dyn Fn() -> std::time::Instant + Sync),
    ) -> (bool, String, u64, Vec<String>) {
        let result = run_gate_steps(
            self.shell,
            &state.brief.verification_cmd,
            &self.root,
            last_failed,
            deadline,
            |ms| self.emit(Event::GateSlotWait { ms }),
            now,
        );
        let failed = result.failures.into_iter().map(|f| f.step).collect();
        (result.passed, result.output, result.wait_ms, failed)
    }

    fn run_step_in(
        &self,
        cmd: &str,
        dir: &Path,
        deadline: Option<std::time::Instant>,
        now: &(dyn Fn() -> std::time::Instant + Sync),
    ) -> (bool, String) {
        run_gate_step(self.shell, cmd, dir, deadline, now)
    }

    fn fingerprint(&self) -> Option<String> {
        let head = self
            .shell
            .exec("git rev-parse HEAD", &self.root, Duration::from_secs(30))
            .ok()?;
        if head.exit_code != 0 {
            return None;
        }
        let status = self
            .shell
            .exec(
                "git status --porcelain",
                &self.root,
                Duration::from_secs(30),
            )
            .ok()?;
        if status.exit_code != 0 {
            return None;
        }
        Some(format!("{}\n{}", head.stdout, status.stdout))
    }

    fn check_blocked_at_base(&self, base_commit: &str, failing_steps: &[String]) -> bool {
        if failing_steps.is_empty() {
            return false;
        }

        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let unique = format!(
            "blyte-base-{}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0),
            COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
        );
        let wt_path = std::env::temp_dir().join(unique);

        let add_cmd = format!(
            "git worktree add --detach {} {}",
            sh_quote(&wt_path.to_string_lossy()),
            sh_quote(base_commit)
        );
        let add_out = match self
            .shell
            .exec(&add_cmd, &self.root, Duration::from_secs(60))
        {
            Ok(o) if o.exit_code == 0 => o,
            _ => return false,
        };
        let _ = add_out;

        struct Guard<'a> {
            shell: &'a dyn Shell,
            root: &'a Path,
            path: PathBuf,
        }
        impl<'a> Drop for Guard<'a> {
            fn drop(&mut self) {
                let cmd = format!(
                    "git worktree remove --force {}",
                    sh_quote(&self.path.to_string_lossy())
                );
                let _ = self.shell.exec(&cmd, self.root, Duration::from_secs(60));
                let _ = std::fs::remove_dir_all(&self.path);
            }
        }

        let _guard = Guard {
            shell: self.shell,
            root: &self.root,
            path: wt_path.clone(),
        };

        let mut all_failed = true;
        for step in failing_steps {
            let (passed, _) = self.run_step_in(step, &wt_path, None, &std::time::Instant::now);
            if passed {
                all_failed = false;
            }
        }
        all_failed
    }

    fn checkpoint(&self) -> Option<String> {
        let out = self
            .shell
            .exec("git rev-parse HEAD", &self.root, Duration::from_secs(30))
            .ok()?;
        (out.exit_code == 0).then(|| out.stdout.trim().to_string())
    }

    /// Problems with report.md's quotes, line citations and unseen names (see `research_check`).
    fn check_report_quotes(&self, seen_names: &HashSet<String>) -> Vec<String> {
        let Ok(raw) = self.fs.read(&self.root.join("report.md")) else {
            return Vec::new();
        };
        // A directive may name only what the `read` tool may read: the workspace and the read
        // roots. Anything else would paste a file the run is not allowed to see into the report.
        let expand_read = |p: &Path| {
            let allowed = tools::resolve_for_read(self.fs, &self.root, &p.to_string_lossy())?;
            self.fs.read(&allowed)
        };
        let (report, mut problems) = quote_expand::expand(&raw, &expand_read);
        if report != raw {
            if let Err(e) = self.fs.write(&self.root.join("report.md"), &report) {
                problems.push(format!(
                    "report.md: could not write the expanded quotes: {e}"
                ));
            }
        }
        let read_roots = tools::read_roots();
        let mut listing = Vec::new();
        // A read root can be any repository; `core.fsmonitor` in its config would run a command
        // on `ls-files` (GitSpawn, 2026-10).
        for dir in std::iter::once(&self.root).chain(read_roots.iter()) {
            if let Ok(o) = self.shell.exec(
                "git -c core.quotePath=off -c core.fsmonitor=false ls-files -co --exclude-standard",
                dir,
                Duration::from_secs(60),
            ) {
                if o.exit_code == 0 {
                    listing.extend(o.stdout.lines().map(|l| dir.join(l)));
                }
            }
        }
        let read = |p: &Path| self.fs.read(p);
        let sources = research_check::Sources {
            workspace: &self.root,
            read_roots: &read_roots,
            listing: &listing,
            read: &read,
        };
        problems.extend(research_check::check(&report, &sources));
        problems.extend(research_check::unseen_names(&report, seen_names));
        problems.extend(research_check::unseen_paths(&report, &sources, seen_names));
        problems
    }

    fn run_claim_check(
        &self,
        deadline: Option<std::time::Instant>,
        now: &(dyn Fn() -> std::time::Instant + Sync),
    ) -> Option<claim_check::ClaimCheck> {
        if !self.claim_check {
            return None;
        }
        let report = self.fs.read(&self.root.join("report.md")).ok()?;
        if report.is_empty() {
            return None;
        }
        let read_roots = tools::read_roots();
        let mut listing = Vec::new();
        for dir in std::iter::once(&self.root).chain(read_roots.iter()) {
            if let Ok(o) = self.shell.exec(
                "git -c core.quotePath=off -c core.fsmonitor=false ls-files -co --exclude-standard",
                dir,
                Duration::from_secs(60),
            ) {
                if o.exit_code == 0 {
                    listing.extend(o.stdout.lines().map(|l| dir.join(l)));
                }
            }
        }
        let read = |p: &Path| self.fs.read(p);
        let claims = research_check::claims(
            &report,
            &research_check::Sources {
                workspace: &self.root,
                read_roots: &read_roots,
                listing: &listing,
                read: &read,
            },
        );
        Some(claim_check::check_claims_with_clock(
            self.provider,
            &claims,
            deadline,
            now,
        ))
    }

    fn reset_to(&self, commit: &str) -> Result<(), String> {
        let out = self
            .shell
            .exec(
                &format!("git reset --hard {commit} && git clean -fd"),
                &self.root,
                Duration::from_secs(120),
            )
            .map_err(|e| format!("could not roll back to {commit}: {e}"))?;
        if out.exit_code != 0 {
            let detail = out.merged();
            let detail = detail.trim();
            return if detail.is_empty() {
                Err(format!(
                    "could not roll back to {commit}: exit {}",
                    out.exit_code
                ))
            } else {
                Err(format!(
                    "could not roll back to {commit}: exit {}: {detail}",
                    out.exit_code
                ))
            };
        }
        Ok(())
    }

    fn elapsed_fraction(
        &self,
        deadline: Option<std::time::Instant>,
        now: &(dyn Fn() -> std::time::Instant + Sync),
    ) -> Option<f64> {
        let max_duration = self.budget.max_duration?;
        let deadline = deadline?;
        let remaining = deadline.saturating_duration_since(now());
        Some(max_duration.saturating_sub(remaining).as_secs_f64() / max_duration.as_secs_f64())
    }

    pub fn run(&self, state: &mut State) -> (Outcome, RunReport) {
        self.run_with_clock(state, &std::time::Instant::now)
    }

    /// Like [`run`](Self::run), reading the current time from `now`.
    pub fn run_with_clock(
        &self,
        state: &mut State,
        now: &(dyn Fn() -> std::time::Instant + Sync),
    ) -> (Outcome, RunReport) {
        self.run_until(state, now, &std::thread::sleep)
    }

    /// Like [`run_with_clock`](Self::run_with_clock), using `sleep` for retry waits.
    pub fn run_with_clock_and_sleep(
        &self,
        state: &mut State,
        now: &(dyn Fn() -> std::time::Instant + Sync),
        sleep: &(dyn Fn(std::time::Duration) + Sync),
    ) -> (Outcome, RunReport) {
        self.run_until(state, now, sleep)
    }

    fn run_until(
        &self,
        state: &mut State,
        now: &(dyn Fn() -> std::time::Instant + Sync),
        sleep: &(dyn Fn(std::time::Duration) + Sync),
    ) -> (Outcome, RunReport) {
        if state.runtime.conversation.is_some()
            && state.runtime.conversation_goal.is_none()
            && !state.brief.goal.starts_with(PEER_MESSAGE_PREFIX)
        {
            state.runtime.conversation_goal = Some(state.brief.goal.clone());
        }

        let pending = std::mem::take(&mut state.runtime.pending_user_parts);
        let make_user_message = |prompt: String| {
            if pending.is_empty() {
                Message::User(prompt)
            } else {
                let mut parts = Vec::with_capacity(1 + pending.len());
                parts.push(UserPart::Text(prompt));
                parts.extend(pending);
                Message::UserParts(parts)
            }
        };

        let mut history = match &state.runtime.conversation {
            None => vec![make_user_message(format!("Begin. {}", state.brief.goal))],
            Some(prev) if prev.is_empty() => {
                vec![make_user_message(format!("Begin. {}", state.brief.goal))]
            }
            Some(prev) => {
                let mut h = prev.clone();
                h.push(make_user_message(state.brief.goal.clone()));
                h
            }
        };

        let goal = match &state.runtime.conversation_goal {
            Some(g) => Some(g.as_str()),
            None if state.brief.goal.starts_with(PEER_MESSAGE_PREFIX) => None,
            None => Some(state.brief.goal.as_str()),
        };
        let system = match self.system_prompt(state, goal) {
            Ok(s) => s,
            Err(err) => {
                if let BaseCheck::Polled(handle) = self.base_check {
                    handle.stop();
                }
                if state.runtime.conversation.is_some() {
                    state.runtime.conversation = Some(history);
                }
                return (Outcome::Error(err), RunReport::default());
            }
        };

        let mut seen_names = HashSet::new();
        if self.research {
            if let Some(g) = goal {
                seen_names.extend(research_check::identifiers(g).map(str::to_owned));
            }
            seen_names.extend(research_check::identifiers(&state.brief.goal).map(str::to_owned));
            // Tool results only: restored user messages include gate feedback that names the
            // very identifiers the check flagged.
            for msg in &history {
                if let Message::ToolResult { content, .. } = msg {
                    seen_names.extend(research_check::identifiers(content).map(str::to_owned));
                }
            }
        }

        let baseline = self.checkpoint();
        let start_fp = self.fingerprint();
        let deadline = self.budget.max_duration.map(|d| now() + d);

        let loop_deadline = match (
            self.research && self.claim_check,
            deadline,
            self.budget.max_duration,
        ) {
            (true, Some(d), Some(max_d)) => d.checked_sub(claim_check_reserve(max_d)).or(deadline),
            _ => deadline,
        };

        let (outcome, mut report) = self.run_loop(
            state,
            &mut history,
            &mut seen_names,
            &system,
            baseline,
            start_fp,
            loop_deadline,
            deadline,
            now,
            sleep,
        );
        if let BaseCheck::Polled(handle) = self.base_check {
            if outcome != Outcome::Verified && report.base_check_passed.is_none() {
                match handle.poll() {
                    BaseCheckState::Pending => {
                        handle.stop();
                    }
                    BaseCheckState::Passed => {
                        report.base_check_passed = Some(true);
                        report.base_check_seconds = handle.elapsed_seconds();
                    }
                    BaseCheckState::Failed { .. } => {
                        report.base_check_passed = Some(false);
                        report.base_check_seconds = handle.elapsed_seconds();
                    }
                }
            }
        }
        if self.research
            && outcome != Outcome::Verified
            && self
                .fs
                .read(&self.root.join("report.md"))
                .is_ok_and(|s| !s.is_empty())
        {
            if report.quote_problems.is_none() {
                let mut problems = self.check_report_quotes(&seen_names);
                problems.truncate(research_check::MAX_PROBLEMS);
                report.quote_problems = Some(problems);
            }
            if report.claim_check.is_none() && report.claim_check_skipped.is_none() {
                if let Some(cc) = self.run_claim_check(deadline, now) {
                    report.usage.input += cc.usage.input;
                    report.usage.cached += cc.usage.cached;
                    report.usage.output += cc.usage.output;
                    report.usage.thinking += cc.usage.thinking;
                    report.claim_check_skipped = cc.skipped.clone();
                    if cc.calls > 0 || cc.skipped.is_none() {
                        report.claim_check = Some(cc);
                    }
                }
            }
        }

        if state.runtime.conversation.is_some() {
            state.runtime.conversation = Some(history);
        }

        (outcome, report)
    }

    #[allow(clippy::too_many_arguments)]
    fn run_loop(
        &self,
        state: &mut State,
        history: &mut Vec<Message>,
        seen_names: &mut HashSet<String>,
        system: &str,
        baseline: Option<String>,
        start_fp: Option<String>,
        deadline: Option<std::time::Instant>,
        claim_deadline: Option<std::time::Instant>,
        now: &(dyn Fn() -> std::time::Instant + Sync),
        sleep: &(dyn Fn(std::time::Duration) + Sync),
    ) -> (Outcome, RunReport) {
        let mut deadline = deadline;
        let mut report = RunReport::default();
        let specs = tools::specs();
        let mut last_sent: Option<Vec<Message>> = None;
        let mut last_failed: Vec<String> = Vec::new();
        let mut last_fingerprint: Option<String> = None;
        let mut call_counts: HashMap<String, u32> = HashMap::new();
        let mut repeats: u32 = 0;
        let mut read_warn_sent = false;
        let mut read_loop_turn: Option<u32> = None;
        let mut change_fp = start_fp.clone();
        let mut progressed = false;
        let mut nudge_turn: Option<u32> = None;
        let mut last_call_sent = false;
        let mut last_turn_called_tools = false;
        let mut last_report = if self.research {
            self.fs.read(&self.root.join("report.md")).ok()
        } else {
            None
        };
        let mut claim_round_done = false;
        let mut prev_turn_start: Option<usize> = None;
        let mut thrash: u32 = 0;
        let mut last_big_read_warn: Option<u32> = None;
        let mut wrap_up_sent = false;
        let mut wrap_up_tools_closed = false;
        let mut wrap_up_report: Option<String> = None;

        if matches!(self.base_check, BaseCheck::BeforeFirstTurn)
            && !gate_steps(&state.brief.verification_cmd).is_empty()
        {
            let bc_start = now();
            let (passed, output, _wait_ms, failing_steps) =
                self.run_gate(state, &[], &mut deadline, now);
            report.base_check_seconds =
                Some(now().saturating_duration_since(bc_start).as_secs_f64());
            report.base_check_passed = Some(passed);
            if !passed {
                let tail = base_check_tail(&output);
                let msg = base_check_blocked_message(&failing_steps, &tail);
                report.final_message = Some(msg.clone());
                return (Outcome::Blocked(msg), report);
            }
        }

        for turn in 1..=self.budget.max_turns {
            if read_loop_turn.is_some_and(|t| turn > t + READ_LOOP_GRACE_TURNS) {
                return (Outcome::BudgetExhausted, report);
            }
            if deadline.is_some_and(|d| now() >= d) {
                return (Outcome::BudgetExhausted, report);
            }
            if let Some(cap) = state.brief.max_cost_usd {
                if let Some(price) = blyte_provider::pricing(&self.provider.model_id()) {
                    if price.cost(&report.usage) >= cap {
                        report.cost_capped = true;
                        return (Outcome::BudgetExhausted, report);
                    }
                }
            }
            if let BaseCheck::Polled(handle) = self.base_check {
                if report.base_check_passed.is_none() {
                    match handle.poll() {
                        BaseCheckState::Pending => {}
                        BaseCheckState::Passed => {
                            report.base_check_passed = Some(true);
                            report.base_check_seconds = handle.elapsed_seconds();
                        }
                        BaseCheckState::Failed { steps, tail } => {
                            report.base_check_passed = Some(false);
                            report.base_check_seconds = handle.elapsed_seconds();
                            let msg = base_check_blocked_message(&steps, &tail);
                            report.final_message = Some(msg.clone());
                            return (Outcome::Blocked(msg), report);
                        }
                    }
                }
            }
            report.outcome_turns = turn;
            let turn_start = history.len();

            if !wrap_up_sent {
                if self.budget.max_turns >= 20 && turn == self.budget.max_turns - 9 {
                    wrap_up_sent = true;
                    history.push(Message::User(format!(
                        "You have 10 turns left of {}. Wrap up now: make sure your work is saved before you run out: committed, or written to the file the task asks for. Then stop calling tools.",
                        self.budget.max_turns
                    )));
                } else if let (Some(max_duration), Some(deadline)) =
                    (self.budget.max_duration, deadline)
                {
                    let time_left = deadline.saturating_duration_since(now());
                    if time_left.as_secs_f64() < max_duration.as_secs_f64() * 0.1 {
                        wrap_up_sent = true;
                        let m = ((time_left.as_secs_f64() / 60.0).ceil() as u64).max(1);
                        let total = ((max_duration.as_secs_f64() / 60.0).ceil() as u64).max(1);
                        history.push(Message::User(format!(
                            "You have about {m} minutes left of {total}. Wrap up now: make sure your work is saved before you run out: committed, or written to the file the task asks for. Then stop calling tools."
                        )));
                    }
                }
                if wrap_up_sent && self.research {
                    wrap_up_tools_closed = true;
                    wrap_up_report = self.fs.read(&self.root.join("report.md")).ok();
                }
            }

            if self.research && turn == RESEARCH_FIRST_REPORT_TURN {
                let has_report = self
                    .fs
                    .read(&self.root.join("report.md"))
                    .is_ok_and(|s| !s.trim().is_empty());
                if !has_report {
                    history.push(Message::User(
                        "Start report.md now with what you have found so far, even if unfinished, then carry on.".to_string(),
                    ));
                }
            }

            if self.research && turn % 30 == 0 {
                let current_report = self.fs.read(&self.root.join("report.md")).ok();
                if current_report == last_report {
                    history.push(Message::User(
                        "Update report.md now with what you have found so far, even if unfinished, then carry on.".to_string(),
                    ));
                }
                last_report = current_report;
            }

            if !self.research
                && state.brief.instructions.is_none()
                && state.runtime.conversation.is_none()
                && !progressed
            {
                let elapsed = self.elapsed_fraction(deadline, now);
                if nudge_turn.is_none()
                    && (turn > NO_PROGRESS_TURNS
                        || (turn > NO_PROGRESS_MIN_TURNS
                            && elapsed.is_some_and(|f| f >= NO_PROGRESS_TIME_FRACTION)))
                {
                    if self.fingerprint() != start_fp {
                        progressed = true;
                    } else {
                        let n = turn - 1;
                        history.push(Message::User(format!(
                            "[blyte] You have spent {n} turns without changing any file or running the gate. Stop exploring and decide now: make the change the task asks for, or, if the task needs no code change or the problem cannot be reproduced, stop calling tools and explain why in your reply."
                        )));
                        nudge_turn = Some(turn);
                    }
                } else if let Some(t) = nudge_turn {
                    if !last_call_sent
                        && (turn >= t + LAST_CALL_TURNS
                            || elapsed.is_some_and(|f| f >= LAST_CALL_TIME_FRACTION))
                    {
                        if self.fingerprint() != start_fp {
                            progressed = true;
                        } else {
                            history.push(Message::User(
                                "[blyte] Still no change after the last reminder. Reply now with your conclusion and why, and do not call any tools: the run stops if this reply calls a tool without changing anything."
                                    .to_string(),
                            ));
                            last_call_sent = true;
                        }
                    } else if last_call_sent && last_turn_called_tools {
                        if self.fingerprint() != start_fp {
                            progressed = true;
                        } else {
                            report.stalled = true;
                            return (Outcome::BudgetExhausted, report);
                        }
                    }
                }
            }

            let fold_budget = self.context.fold_budget(history);
            if let Some(prev_start) = prev_turn_start {
                if let Some(budget) = fold_budget {
                    let n: usize = history[prev_start..]
                        .iter()
                        .filter(|m| matches!(m, Message::ToolResult { .. }))
                        .map(crate::context::approx_tokens)
                        .sum();
                    if n > budget / 2 {
                        report.big_read_turns += 1;
                        if last_big_read_warn.is_none_or(|last| turn >= last + 5) {
                            last_big_read_warn = Some(turn);
                            history.push(Message::User(format!(
                                "[blyte] Your last turn's tool output was about {n} tokens, more than half of what stays in context ({budget}). Read narrower ranges so it is not dropped before you use it."
                            )));
                        }
                    }
                }
                if self
                    .context
                    .folds(history)
                    .last()
                    .is_some_and(|&(_, b)| b + 1 > prev_start)
                {
                    thrash += 1;
                    if thrash >= 5 {
                        report.fold_thrash = true;
                        return (Outcome::BudgetExhausted, report);
                    }
                    if thrash == 2 {
                        let budget = fold_budget.unwrap_or_default();
                        history.push(Message::User(format!(
                            "[blyte] Your recent tool results are being dropped from your context because each turn reads more than fits (about {budget} tokens stay verbatim). Read narrower ranges (at most 200 lines), one or two files per turn, and act on what you have read before reading more."
                        )));
                    }
                } else {
                    thrash = 0;
                }
            }
            prev_turn_start = Some(turn_start);

            let mut req = Request {
                system: system.to_string(),
                messages: self.context.build(state, history),
                tools: specs.clone(),
                max_output_tokens: None,
                timeout: None,
            };
            let (appended, new_chars) = match &last_sent {
                Some(prev)
                    if req.messages.len() >= prev.len()
                        && req.messages[..prev.len()] == prev[..] =>
                {
                    (
                        true,
                        req.messages[prev.len()..].iter().map(message_chars).sum(),
                    )
                }
                _ => (false, req.messages.iter().map(message_chars).sum()),
            };
            last_sent = Some(req.messages.clone());
            // A burst rate limit ended a run after 28 calls (2026-09-23). Transient failures are
            // waited out, but never past the deadline: a run that cannot finish in time reports.
            let model_start = now();
            let mut attempt = 0;
            let mut failed_attempts: Vec<FailedAttempt> = Vec::new();
            let (resp, call_start) = loop {
                if let Some(d) = deadline {
                    let time_left = d.saturating_duration_since(now());
                    if time_left.is_zero() {
                        return (Outcome::BudgetExhausted, report);
                    }
                    req.timeout = Some(time_left);
                }
                let call_start = std::time::Instant::now();
                match self.provider.complete(&req) {
                    Ok(r) => break (r, call_start),
                    Err(e) => {
                        let (u_in, u_cached, u_out, u_think) = match &e {
                            ProviderError::NoAnswer { usage, .. } => {
                                report.usage.input += usage.input;
                                report.usage.cached += usage.cached;
                                report.usage.output += usage.output;
                                report.usage.thinking += usage.thinking;
                                (usage.input, usage.cached, usage.output, usage.thinking)
                            }
                            _ => (0, 0, 0, 0),
                        };
                        let push_deadline_turn = |report: &mut RunReport| {
                            let timing = self.provider.last_stream_timing().unwrap_or_default();
                            report.turn_usage.push(TurnUsage {
                                turn,
                                input: u_in,
                                cached: u_cached,
                                output: u_out,
                                thinking: u_think,
                                prompt_messages: req.messages.len(),
                                appended,
                                new_chars,
                                fold_budget,
                                model_ms: now().saturating_duration_since(model_start).as_millis()
                                    as u64,
                                tools_ms: 0,
                                first_data_ms: timing.first_data_ms,
                                max_gap_ms: timing.max_gap_ms,
                                failed_attempts: failed_attempts.clone(),
                            });
                        };
                        // An exhausted quota is reported as an error even past the deadline:
                        // the operator needs to see it to switch provider.
                        if quota_exhausted(&e).is_none() && deadline.is_some_and(|d| now() >= d) {
                            push_deadline_turn(&mut report);
                            return (Outcome::BudgetExhausted, report);
                        }
                        let max_retries = max_retries_for(&e);
                        if is_transient(&e) && attempt < max_retries {
                            let elapsed = call_start.elapsed().as_secs_f64().round() as u64;
                            let s = if elapsed > 0 {
                                elapsed
                            } else {
                                blyte_provider::model_timeout_secs()
                            };
                            attempt += 1;
                            let wait = retry_wait(&e, attempt);
                            if deadline.is_some_and(|d| now() + wait >= d) {
                                push_deadline_turn(&mut report);
                                return (Outcome::BudgetExhausted, report);
                            }
                            report.provider_retries += 1;
                            let timing = self.provider.last_stream_timing().unwrap_or_default();
                            failed_attempts.push(FailedAttempt {
                                elapsed_ms: call_start.elapsed().as_millis() as u64,
                                timed_out: e.is_timeout(),
                                first_data_ms: timing.first_data_ms,
                                max_gap_ms: timing.max_gap_ms,
                            });
                            let reason = if e.is_timeout() {
                                format!(
                                    "model call timed out after {s} s; retrying ({attempt} of {max_retries}; raise BLYTE_MODEL_IDLE_TIMEOUT_SECS for silence or BLYTE_MODEL_TIMEOUT_SECS for whole call)"
                                )
                            } else {
                                format!(
                                    "provider: {e}; retrying in {}s ({attempt}/{max_retries})",
                                    wait.as_secs()
                                )
                            };
                            eprintln!("{reason}");
                            self.emit(Event::Retry {
                                attempt,
                                max: max_retries,
                                wait_ms: wait.as_millis() as u64,
                                reason,
                            });
                            sleep(wait);
                        } else {
                            let err_msg = match quota_exhausted(&e) {
                                Some(msg) => format!("{msg}: {e}"),
                                None => e.to_string(),
                            };
                            return (Outcome::Error(err_msg), report);
                        }
                    }
                }
            };
            let model_ms = now().saturating_duration_since(model_start).as_millis() as u64;
            let timing: StreamTiming = self.provider.last_stream_timing().unwrap_or_default();
            report.usage.input += resp.usage.input;
            report.usage.cached += resp.usage.cached;
            report.usage.output += resp.usage.output;
            report.usage.thinking += resp.usage.thinking;
            report.turn_usage.push(TurnUsage {
                turn,
                input: resp.usage.input,
                cached: resp.usage.cached,
                output: resp.usage.output,
                thinking: resp.usage.thinking,
                prompt_messages: req.messages.len(),
                appended,
                new_chars,
                fold_budget,
                model_ms,
                tools_ms: 0,
                first_data_ms: timing.first_data_ms,
                max_gap_ms: timing.max_gap_ms,
                failed_attempts,
            });

            let has_output = !resp.text.is_empty()
                || !resp.tool_calls.is_empty()
                || resp.usage.output > 0
                || resp.usage.thinking > 0;
            if has_output {
                if let Some(first_data_ms) = timing.first_data_ms {
                    let at = (call_start + Duration::from_millis(first_data_ms))
                        .min(std::time::Instant::now());
                    self.emit(Event::FirstOutput { at });
                }
            }

            let trimmed = resp.text.trim();
            self.emit(Event::Turn {
                n: turn,
                text: trimmed,
                usage: resp.usage,
            });
            if truncated(resp.finish_reason.as_deref()) {
                last_turn_called_tools = false;
                report.truncated_turns += 1;
                history.push(Message::User(
                    "Your last reply hit the output token limit and was cut off, so none of it was used. Reply again more briefly: make one tool call at a time and keep edits small.".to_string(),
                ));
                continue;
            }
            if trimmed.is_empty() && resp.tool_calls.is_empty() {
                report.empty_turns += 1;
            }
            if !trimmed.is_empty() {
                report.final_message = Some(trimmed.to_string());
                history.push(Message::Assistant(resp.text.clone()));
            }

            // --- the model is still working -------------------------------------------------
            if !resp.tool_calls.is_empty() {
                last_turn_called_tools = true;
                let tools_start = now();
                // A turn's calls are recorded together, then its results together, in call
                // order. Providers encode one model turn carrying several calls and one reply
                // carrying their results; interleaving them split a parallel batch into turns
                // Gemini rejects (it signs only the first call of a batch).
                for call in &resp.tool_calls {
                    history.push(Message::ToolCall {
                        id: call.id.clone(),
                        name: call.name.clone(),
                        arguments: call.arguments.clone(),
                        signature: call.signature.clone(),
                    });
                }
                let current_fp = self.fingerprint();
                if current_fp != start_fp {
                    progressed = true;
                }
                if current_fp != change_fp {
                    call_counts.clear();
                    repeats = 0;
                    read_warn_sent = false;
                    change_fp = current_fp;
                }
                for call in &resp.tool_calls {
                    if deadline.is_some_and(|d| now() >= d) {
                        report.turn_usage.last_mut().unwrap().tools_ms =
                            now().saturating_duration_since(tools_start).as_millis() as u64;
                        return (Outcome::BudgetExhausted, report);
                    }
                    report.tool_calls += 1;
                    *report.tool_counts.entry(call.name.clone()).or_default() += 1;

                    if wrap_up_tools_closed
                        && self
                            .fs
                            .read(&self.root.join("report.md"))
                            .ok()
                            .is_some_and(|s| {
                                !s.is_empty() && Some(s.as_str()) != wrap_up_report.as_deref()
                            })
                    {
                        wrap_up_tools_closed = false;
                    }
                    let read_closed = read_loop_turn.is_some()
                        && matches!(call.name.as_str(), "read" | "grep" | "glob");
                    let wrap_up_closed =
                        wrap_up_tools_closed && !matches!(call.name.as_str(), "write" | "edit");
                    let tool_closed = read_closed || wrap_up_closed;
                    let input = if call.name == "read" {
                        extract_action_target(&call.name, &call.arguments)
                            .chars()
                            .take(100)
                            .collect()
                    } else {
                        let clean = |s: &str| s.trim_end().replace('\n', " ↵ ");
                        let text = if call.name == "blyte" {
                            format_blyte_tool_input(&call.arguments)
                                .map(|s| clean(&s))
                                .unwrap_or_else(|| clean(&call.arguments.to_string()))
                        } else {
                            call.arguments
                                .get("command")
                                .or_else(|| call.arguments.get("pattern"))
                                .or_else(|| call.arguments.get("path"))
                                .and_then(|v| v.as_str())
                                .map(clean)
                                .unwrap_or_else(|| clean(&call.arguments.to_string()))
                        };
                        if text.chars().count() > 2000 {
                            let mut cut: String = text.chars().take(2000).collect();
                            cut.push('…');
                            cut
                        } else {
                            text
                        }
                    };
                    self.emit(Event::ToolStart {
                        name: &call.name,
                        input: input.clone(),
                    });
                    let mut outcome = if read_closed {
                        tools::ToolOutcome {
                            content: "[blyte] reading is closed; write report.md now from what you have found.".to_string(),
                            is_error: true,
                        }
                    } else if wrap_up_closed {
                        tools::ToolOutcome {
                            content: "[blyte] almost out of budget: write report.md now (write or edit). Other tools are closed until report.md has changed.".to_string(),
                            is_error: true,
                        }
                    } else {
                        let tool_timeout = deadline
                            .map(|d| d.saturating_duration_since(now()))
                            // No run deadline: each tool's own ceiling applies (300 s for most,
                            // longer for `blyte edit-finish`, which runs the check).
                            .unwrap_or(Duration::MAX);
                        tools::execute_with_timeout(
                            &self.root,
                            self.shell,
                            self.fs,
                            &call.name,
                            &call.arguments,
                            tool_timeout,
                        )
                    };

                    let summary = outcome
                        .content
                        .lines()
                        .next()
                        .unwrap_or("")
                        .chars()
                        .take(90)
                        .collect::<String>();
                    self.emit(Event::Tool {
                        name: &call.name,
                        input,
                        summary,
                        is_error: outcome.is_error,
                    });

                    if self.research && !tool_closed {
                        seen_names.extend(
                            research_check::identifiers(&outcome.content).map(str::to_owned),
                        );
                    }
                    if !outcome.is_error && matches!(call.name.as_str(), "edit" | "write") {
                        progressed = true;
                        call_counts.clear();
                        repeats = 0;
                        read_warn_sent = false;
                    } else if !tool_closed && matches!(call.name.as_str(), "read" | "grep" | "glob")
                    {
                        let key = format!("{}:{}", call.name, call.arguments);
                        let n = call_counts.entry(key).or_insert(0);
                        *n += 1;
                        let n = *n;
                        if n >= 2 {
                            repeats += 1;
                            report.peak_read_repeats = report.peak_read_repeats.max(repeats);
                        }
                        if n >= 3 {
                            let tail = if self.research {
                                "write what you need into report.md"
                            } else {
                                "and make your change"
                            };
                            outcome.content.push_str(&format!(
                                "\n\n[blyte] You have made this exact call {n} times since the workspace last changed; earlier results were dropped from your context to save space. Do not read it again: note what you need from it in your reply, read only the lines you need, {tail}."
                            ));
                        }
                        if self.research && !read_warn_sent && repeats >= READ_LOOP_WARN {
                            read_warn_sent = true;
                            outcome.content.push_str(&format!(
                                "\n\n[blyte] You have re-read {READ_LOOP_WARN} files or searches since the workspace last changed; earlier results were dropped to save space. Write what you need into report.md now; reading stops at {READ_LOOP_LIMIT}."
                            ));
                        }
                    }
                    history.push(Message::ToolResult {
                        id: call.id.clone(),
                        name: call.name.clone(),
                        content: outcome.content,
                        is_error: outcome.is_error,
                    });
                    if repeats >= READ_LOOP_LIMIT && read_loop_turn.is_none() {
                        report.read_loop = true;
                        if !self.research {
                            report.turn_usage.last_mut().unwrap().tools_ms =
                                now().saturating_duration_since(tools_start).as_millis() as u64;
                            return (Outcome::BudgetExhausted, report);
                        }
                        read_loop_turn = Some(turn);
                    }
                }
                if read_loop_turn == Some(turn) {
                    history.push(Message::User(
                        "[blyte] Stop reading; write report.md now from what you have found, mark what you could not confirm as open questions, then stop calling tools.".to_string(),
                    ));
                }
                report.turn_usage.last_mut().unwrap().tools_ms =
                    now().saturating_duration_since(tools_start).as_millis() as u64;
                continue;
            }

            // --- the model stopped calling tools: the runtime decides -----------------------
            last_turn_called_tools = false;
            if report.gate_attempts > 0
                && CLAIM_PHRASES
                    .iter()
                    .any(|&p| resp.text.to_lowercase().contains(p))
            {
                if let (Some(last_fp), Some(curr_fp), Some(base_commit)) =
                    (&last_fingerprint, self.fingerprint(), &baseline)
                {
                    if *last_fp == curr_fp && self.check_blocked_at_base(base_commit, &last_failed)
                    {
                        let steps = last_failed.join("; ");
                        let text: String = resp.text.chars().take(300).collect();
                        return (
                            Outcome::Blocked(format!(
                                "the check fails at the base commit too ({steps}); the model said: {text}"
                            )),
                            report,
                        );
                    }
                }
            }

            if state.brief.verification_cmd.trim().is_empty() {
                if state.brief.instructions.is_some() {
                    return (Outcome::Finished, report);
                }
                self.finalize_polled_base_check(&mut report);
                return (Outcome::Verified, report);
            }

            progressed = true;
            report.gate_attempts += 1;
            report.gate_turns.push(turn);
            self.emit(Event::GateStart {
                attempt: report.gate_attempts,
            });
            let gate_start = now();
            let (mut passed, mut output, wait_ms, failing) =
                self.run_gate(state, &last_failed, &mut deadline, now);
            last_failed = failing;
            if passed && self.research {
                let mut problems = self.check_report_quotes(seen_names);
                if !problems.is_empty() {
                    passed = false;
                    output = format!("exit 1\n{}", research_check::render(&problems));
                }
                problems.truncate(research_check::MAX_PROBLEMS);
                report.quote_problems = Some(problems);
                if passed {
                    if let Some(cc) = self.run_claim_check(claim_deadline, now) {
                        report.usage.input += cc.usage.input;
                        report.usage.cached += cc.usage.cached;
                        report.usage.output += cc.usage.output;
                        report.usage.thinking += cc.usage.thinking;
                        report.claim_check_skipped = cc.skipped.clone();
                        if !cc.contradicted.is_empty() && !claim_round_done {
                            claim_round_done = true;
                            passed = false;
                            let mut lines: Vec<String> = cc
                                .contradicted
                                .iter()
                                .map(|f| {
                                    let text: String = f.text.chars().take(200).collect();
                                    format!("report.md:{}: {text}\n  checker: {}", f.line, f.reason)
                                })
                                .collect();
                            lines.push(
                                "These claims do not match the lines they cite. Fix each claim, cite the lines that support it, or remove it."
                                    .to_string(),
                            );
                            output = format!("exit 1\n{}", lines.join("\n"));
                        }
                        if cc.calls > 0 || cc.skipped.is_none() {
                            report.claim_check = Some(cc);
                        }
                    }
                }
            }
            report
                .gate_ms
                .push(now().saturating_duration_since(gate_start).as_millis() as u64);
            report.gate_wait_ms.push(wait_ms);
            self.emit(Event::Gate {
                attempt: report.gate_attempts,
                passed,
                output: output.lines().next().unwrap_or(""),
            });
            if passed {
                self.finalize_polled_base_check(&mut report);
                return (Outcome::Verified, report);
            }
            report.gate_failures.push(cut_gate_output(&output));
            if deadline.is_some_and(|d| now() >= d) {
                return (Outcome::BudgetExhausted, report);
            }

            last_fingerprint = self.fingerprint();
            if last_fingerprint != start_fp {
                progressed = true;
            }

            if self.rollback {
                if let Some(base) = &baseline {
                    if let Err(msg) = self.reset_to(base) {
                        return (Outcome::Error(msg), report);
                    }
                    state.runtime.rollbacks += 1;
                    let short_sha = &base[..base.len().min(8)];
                    self.emit(Event::RolledBack { to: short_sha });
                }
            }
            if report.gate_attempts >= self.budget.max_gate_attempts {
                return (Outcome::GateFailed, report);
            }

            // Fed back as an observation, not a request to try harder. The worker is told what
            // the command said and, if the tree was reset, that its edits are gone -- silently
            // resetting would leave it editing against a file it no longer has.
            let reset_note = if self.rollback && baseline.is_some() {
                "\n\nYour changes have been reverted to the last verified state. Start from \
                 the current files, not from what you remember writing."
            } else {
                ""
            };
            let advice = if self.research {
                "Fix report.md as listed above, then reply with one line."
            } else {
                "If the failure is caused by your change, fix your change, not the machine. \
                 If it is not caused by your change (disk space, network, a missing service), \
                 say so and stop."
            };
            history.push(Message::User(format!(
                "Verification did not pass.\n\n{output}\n\n{advice}{reset_note}"
            )));
        }
        (Outcome::BudgetExhausted, report)
    }

    fn finalize_polled_base_check(&self, report: &mut RunReport) {
        let BaseCheck::Polled(handle) = self.base_check else {
            return;
        };
        if report.base_check_passed == Some(true) {
            if report.base_check_seconds.is_none() {
                report.base_check_seconds = handle.elapsed_seconds();
            }
            return;
        }
        let final_state = match handle.poll() {
            BaseCheckState::Pending => handle.wait(),
            other => other,
        };
        report.base_check_seconds = handle.elapsed_seconds();
        match final_state {
            BaseCheckState::Passed => {
                report.base_check_passed = Some(true);
            }
            BaseCheckState::Failed { .. } => {
                report.base_check_passed = Some(false);
                let note = "the check failed on the untouched code but passes with this change";
                report.final_message = Some(match report.final_message.take() {
                    Some(existing) if !existing.is_empty() => format!("{existing}\n\n{note}"),
                    _ => note.to_string(),
                });
            }
            BaseCheckState::Pending => {}
        }
    }
}

/// A single failing gate step and its bounded output.
const SANDBOX_DENIAL_HINT: &str = "hint: \"Operation not permitted\" usually means blyte's sandbox denied a path outside the worktree (for example a .env in the main checkout). Make the check independent of files outside the worktree.";

/// Returns a sandbox hint when `output` mentions `operation not permitted` in any letter case.
pub fn sandbox_denial_hint(output: &str) -> Option<&'static str> {
    if output
        .to_ascii_lowercase()
        .contains("operation not permitted")
    {
        Some(SANDBOX_DENIAL_HINT)
    } else {
        None
    }
}

fn append_hint_line(output: &mut String, hint: &str) {
    if output.trim_end_matches(['\r', '\n']).ends_with(hint) {
        return;
    }
    if !output.ends_with('\n') {
        output.push('\n');
    }
    output.push_str(hint);
}

fn attach_sandbox_denial_hint(result: &mut GateRunResult) {
    if result.passed {
        return;
    }
    let hint = sandbox_denial_hint(&result.output).or_else(|| {
        result
            .failures
            .iter()
            .find_map(|f| sandbox_denial_hint(&f.output))
    });
    let Some(hint) = hint else {
        return;
    };
    append_hint_line(&mut result.output, hint);
    if let Some(last) = result.failures.last_mut() {
        append_hint_line(&mut last.output, hint);
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GateStepFailure {
    pub step: String,
    pub output: String,
}

/// Result of running a verification gate across all of its steps.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GateRunResult {
    pub passed: bool,
    pub output: String,
    pub wait_ms: u64,
    pub failures: Vec<GateStepFailure>,
}

/// Run one gate step in `dir` through `shell`, returning `(passed, bounded_output)`.
pub fn run_gate_step(
    shell: &dyn Shell,
    cmd: &str,
    dir: &Path,
    deadline: Option<std::time::Instant>,
    now: &(dyn Fn() -> std::time::Instant + Sync),
) -> (bool, String) {
    let timeout = match deadline {
        Some(d) => {
            let left = d.saturating_duration_since(now());
            if left.is_zero() {
                return (false, "exit 124\ngate ran out of time".into());
            }
            Duration::from_secs(1800).min(left)
        }
        None => Duration::from_secs(1800),
    };
    let wrapped = format!("(export {}=1\n{cmd}\n)", gate_slots::IN_GATE_ENV);
    match shell.exec(&wrapped, dir, timeout) {
        Ok(o) => {
            let merged = o.merged();
            let raw = merged.trim_end();
            let body = tools::bound_output(raw);
            let dropped: Vec<&str> = if o.exit_code != 0 {
                let kept: std::collections::HashSet<&str> = body.lines().map(str::trim).collect();
                summary_lines(raw)
                    .into_iter()
                    .filter(|l| !kept.contains(l))
                    .collect()
            } else {
                Vec::new()
            };
            let content = if dropped.is_empty() {
                body
            } else {
                let block = format!("Failing, in lines blyte left out:\n{}", dropped.join("\n"));
                if body.is_empty() {
                    block
                } else {
                    format!("{block}\n\n{body}")
                }
            };
            if o.exit_code != 0 && deadline.is_some_and(|d| now() >= d) {
                if content.is_empty() {
                    return (false, format!("exit {}\ngate ran out of time", o.exit_code));
                }
                return (
                    false,
                    format!("exit {}\ngate ran out of time\n{content}", o.exit_code),
                );
            }
            (o.exit_code == 0, format!("exit {}\n{content}", o.exit_code))
        }
        Err(e) => {
            if deadline.is_some_and(|d| now() >= d) {
                return (false, format!("gate ran out of time: {e}"));
            }
            (false, format!("verification command could not run: {e}"))
        }
    }
}

/// Run a multi-line verification gate in `dir` through `shell`, acquiring a gate slot if enabled.
pub fn run_gate_steps(
    shell: &dyn Shell,
    gate: &str,
    dir: &Path,
    last_failed: &[String],
    deadline: &mut Option<std::time::Instant>,
    on_slot_wait: impl FnOnce(u64),
    now: &(dyn Fn() -> std::time::Instant + Sync),
) -> GateRunResult {
    run_gate_steps_cancellable(
        shell,
        gate,
        dir,
        last_failed,
        deadline,
        on_slot_wait,
        now,
        None,
    )
}

/// Run a multi-line verification gate in `dir` through `shell`, stopping early if `cancel` is triggered.
#[allow(clippy::too_many_arguments)]
pub fn run_gate_steps_cancellable(
    shell: &dyn Shell,
    gate: &str,
    dir: &Path,
    last_failed: &[String],
    deadline: &mut Option<std::time::Instant>,
    on_slot_wait: impl FnOnce(u64),
    now: &(dyn Fn() -> std::time::Instant + Sync),
    cancel: Option<&crate::shell::CancelHandle>,
) -> GateRunResult {
    let (_guard, wait_ms) = if gate_slots::enabled() && !gate_slots::nested() {
        let max_slots = gate_slots::slots();
        let slot_dir = gate_slots::slot_dir();
        match gate_slots::acquire_cancellable(
            max_slots,
            &slot_dir,
            Duration::from_millis(500),
            cancel.map(crate::shell::CancelHandle::flag),
        ) {
            Ok(Some((guard, waited))) => {
                let wait_ms = waited.as_millis() as u64;
                if let Some(d) = deadline.as_mut() {
                    *d += waited;
                }
                if wait_ms > 0 {
                    eprintln!(
                        "gate: waited {}s for a gate slot ({max_slots} in use)",
                        waited.as_secs()
                    );
                    on_slot_wait(wait_ms);
                }
                (Some(guard), wait_ms)
            }
            Ok(None) => {
                return GateRunResult {
                    passed: false,
                    output: "cancelled".into(),
                    wait_ms: 0,
                    failures: Vec::new(),
                };
            }
            Err(e) => {
                eprintln!("gate: slot acquisition failed: {e}");
                (None, 0)
            }
        }
    } else {
        (None, 0)
    };

    if cancel.is_some_and(crate::shell::CancelHandle::is_cancelled) {
        return GateRunResult {
            passed: false,
            output: "cancelled".into(),
            wait_ms,
            failures: Vec::new(),
        };
    }

    let steps = gate_steps(gate);
    if steps.len() <= 1 {
        let step_cmd = steps.first().copied().unwrap_or(gate);
        let (passed, output) = run_gate_step(shell, step_cmd, dir, *deadline, now);
        let failures = if passed {
            Vec::new()
        } else {
            vec![GateStepFailure {
                step: step_cmd.to_string(),
                output: output.clone(),
            }]
        };
        let mut result = GateRunResult {
            passed,
            output,
            wait_ms,
            failures,
        };
        attach_sandbox_denial_hint(&mut result);
        return result;
    }
    let (first_group, second_group) = {
        let (f, s) = retry_order(&steps, last_failed);
        if f.is_empty() {
            (steps.clone(), Vec::new())
        } else {
            (f, s)
        }
    };
    let mut formatted_failures = Vec::new();
    let mut failures = Vec::new();
    for &step in &first_group {
        if cancel.is_some_and(crate::shell::CancelHandle::is_cancelled) {
            break;
        }
        let (passed, output) = run_gate_step(shell, step, dir, *deadline, now);
        if !passed {
            formatted_failures.push(format!("$ {step}\n{output}"));
            failures.push(GateStepFailure {
                step: step.to_string(),
                output,
            });
            if deadline.is_some_and(|d| now() >= d)
                || cancel.is_some_and(crate::shell::CancelHandle::is_cancelled)
            {
                break;
            }
        }
    }
    if !failures.is_empty() {
        let body = tools::bound_output(&formatted_failures.join("\n\n"));
        let failed_names: Vec<&str> = failures.iter().map(|f| f.step.as_str()).collect();
        let not_rerun = if !second_group.is_empty() {
            format!(
                "\nNot re-run this attempt: {} step(s) that passed last time ({}).",
                second_group.len(),
                second_group.join(", ")
            )
        } else {
            String::new()
        };
        let mut result = GateRunResult {
            passed: false,
            output: format!(
                "{} of {} steps failed: {}{not_rerun}\n\n{body}",
                failures.len(),
                steps.len(),
                failed_names.join(", ")
            ),
            wait_ms,
            failures,
        };
        attach_sandbox_denial_hint(&mut result);
        return result;
    }
    for &step in &second_group {
        if cancel.is_some_and(crate::shell::CancelHandle::is_cancelled) {
            break;
        }
        let (passed, output) = run_gate_step(shell, step, dir, *deadline, now);
        if !passed {
            formatted_failures.push(format!("$ {step}\n{output}"));
            failures.push(GateStepFailure {
                step: step.to_string(),
                output,
            });
            if deadline.is_some_and(|d| now() >= d)
                || cancel.is_some_and(crate::shell::CancelHandle::is_cancelled)
            {
                break;
            }
        }
    }
    if failures.is_empty() {
        return GateRunResult {
            passed: true,
            output: "exit 0".into(),
            wait_ms,
            failures: Vec::new(),
        };
    }
    let body = tools::bound_output(&formatted_failures.join("\n\n"));
    let failed_names: Vec<&str> = failures.iter().map(|f| f.step.as_str()).collect();
    let mut result = GateRunResult {
        passed: false,
        output: format!(
            "{} of {} steps failed: {}\n\n{body}",
            failures.len(),
            steps.len(),
            failed_names.join(", ")
        ),
        wait_ms,
        failures,
    };
    attach_sandbox_denial_hint(&mut result);
    result
}

/// The steps of a gate: its non-blank lines, trimmed.
pub fn gate_steps(gate: &str) -> Vec<&str> {
    gate.lines()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .collect()
}

/// Splits `steps` into (the steps whose text is in `last_failed`, in gate order; the
/// others, in gate order). With an empty `last_failed`, returns (all steps, nothing).
pub fn retry_order<'a>(steps: &[&'a str], last_failed: &[String]) -> (Vec<&'a str>, Vec<&'a str>) {
    if last_failed.is_empty() {
        return (steps.to_vec(), Vec::new());
    }
    let mut failed = Vec::new();
    let mut others = Vec::new();
    for &step in steps {
        if last_failed.iter().any(|f| f == step) {
            failed.push(step);
        } else {
            others.push(step);
        }
    }
    (failed, others)
}

/// Summary lines from test runners (cargo, pytest, rustc).
fn is_summary_line(line: &str) -> bool {
    let t = line.trim();
    ((t.starts_with("FAILED ") || t.starts_with("ERROR "))
        && (t.contains("::") || t.contains(".py")))
        || (t.starts_with('=') && (t.contains(" failed") || t.contains(" error")))
        || (t.starts_with("test ") && t.ends_with("FAILED"))
        || t.starts_with("error[")
        || t.starts_with("error:")
        || t.starts_with("test result: FAILED")
}

/// Collects up to 40 unique summary lines in order of appearance.
fn summary_lines(output: &str) -> Vec<&str> {
    let mut lines = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for line in output.lines() {
        let t = line.trim();
        if is_summary_line(t) && seen.insert(t) {
            lines.push(t);
            if lines.len() == 40 {
                break;
            }
        }
    }
    lines
}

/// Checks if a line matches blyte's own "N of M steps failed: …" header format.
fn is_blyte_header(line: &str) -> bool {
    let t = line.trim();
    let Some((n, rest)) = t.split_once(" of ") else {
        return false;
    };
    if !n.chars().all(|c| c.is_ascii_digit()) || n.is_empty() {
        return false;
    }
    let Some((m, _)) = rest.split_once(" steps failed:") else {
        return false;
    };
    m.chars().all(|c| c.is_ascii_digit()) && !m.is_empty()
}

/// Cuts gate output longer than 4,000 characters, keeping test runner summary lines,
/// the header, and the head and tail.
pub fn cut_gate_output(output: &str) -> String {
    const MAX_CHARS: usize = 4_000;

    let total_chars = output.chars().count();
    if total_chars <= MAX_CHARS {
        return output.to_string();
    }

    let sum_lines = summary_lines(output);
    let has_summary = !sum_lines.is_empty();

    let first_line = output.lines().next().unwrap_or("");
    let has_blyte_header = is_blyte_header(first_line);

    let (header, rem) = if has_summary && has_blyte_header {
        let rem = &output[first_line.len()..];
        let rem = rem.trim_start_matches(['\r', '\n']);
        (Some(first_line), rem)
    } else {
        (None, output)
    };

    let summary_block = if has_summary {
        let mut block = String::from("Failing, from the full output:\n");
        block.push_str(&sum_lines.join("\n"));
        Some(block)
    } else {
        None
    };

    let prefix_chars = header.map(|h| h.chars().count() + 1).unwrap_or(0)
        + summary_block
            .as_ref()
            .map(|s| s.chars().count() + 1)
            .unwrap_or(0);

    let available = MAX_CHARS.saturating_sub(prefix_chars);
    let head_budget = available / 4;
    let tail_budget = available - head_budget;

    let head = if head_budget == 0 || rem.is_empty() {
        ""
    } else {
        let head_cand_end = rem
            .char_indices()
            .nth(head_budget)
            .map(|(i, _)| i)
            .unwrap_or(rem.len());
        let head_cand = &rem[..head_cand_end];
        match head_cand.rfind('\n') {
            Some(idx) => &head_cand[..idx],
            None => head_cand,
        }
    };

    let tail = if tail_budget == 0 {
        ""
    } else {
        let tail_cand_start = output
            .char_indices()
            .nth(total_chars.saturating_sub(tail_budget))
            .map(|(i, _)| i)
            .unwrap_or(output.len());
        let tail_cand = &output[tail_cand_start..];
        match tail_cand.find('\n') {
            Some(idx) => &tail_cand[idx + 1..],
            None => tail_cand,
        }
    };

    let dropped = total_chars.saturating_sub(head.chars().count() + tail.chars().count());

    let mut pieces = Vec::new();
    if let Some(h) = header {
        pieces.push(h);
    }
    if let Some(sb) = &summary_block {
        pieces.push(sb.as_str());
    }
    if !head.is_empty() {
        pieces.push(head);
    }
    let marker = format!("… [{dropped} characters cut] …");
    pieces.push(&marker);
    if !tail.is_empty() {
        pieces.push(tail);
    }
    let mut joined = pieces.join("\n");
    if output
        .trim_end_matches(['\r', '\n'])
        .ends_with(SANDBOX_DENIAL_HINT)
    {
        append_hint_line(&mut joined, SANDBOX_DENIAL_HINT);
    }
    joined
}

fn format_blyte_arg(arg: &str) -> String {
    if arg.is_empty()
        || arg
            .chars()
            .any(|c| c.is_whitespace() || c == '"' || c == '\'')
    {
        serde_json::to_string(arg).unwrap_or_else(|_| format!("\"{arg}\""))
    } else {
        arg.to_string()
    }
}

pub fn format_blyte_tool_input(args: &serde_json::Value) -> Option<String> {
    let raw_args = args.get("args")?.as_array()?;
    let mut parts = Vec::with_capacity(raw_args.len() + 1);
    parts.push("blyte".to_string());
    for item in raw_args {
        parts.push(format_blyte_arg(item.as_str()?));
    }
    let mut cmd = parts.join(" ");
    if args.get("background").and_then(|v| v.as_bool()) == Some(true) {
        cmd.push_str(" (background)");
    }
    Some(cmd)
}

/// Extracts a concise, human-readable target descriptor from a tool call's arguments.
///
/// Deterministic and zero-latency: formats tool targets without LLM invocation to
/// bound the prompt footprint in episodic action ledgers.
///
/// # Arguments
/// * `tool` - The name of the tool invoked (e.g. "read", "bash", "write").
/// * `args` - The JSON arguments supplied to the tool.
///
/// # Returns
/// A compact string identifying the target file, command, or parameter.
pub fn extract_action_target(tool: &str, args: &serde_json::Value) -> String {
    // Discriminate on known tool types to extract their canonical target representations.
    match tool {
        "read" => {
            // Extract the target file path and optionally the requested line range.
            if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
                let start = args.get("start_line").and_then(|v| {
                    v.as_u64()
                        .map(|n| n.to_string())
                        .or_else(|| v.as_str().map(|s| s.to_string()))
                });
                let end = args.get("end_line").and_then(|v| {
                    v.as_u64()
                        .map(|n| n.to_string())
                        .or_else(|| v.as_str().map(|s| s.to_string()))
                });
                // When line bounds are specified, annotate the path with 1-indexed line boundaries.
                match (start, end) {
                    (Some(s), Some(e)) => return format!("{path} (L{s}-L{e})"),
                    (Some(s), None) => return format!("{path} (L{s}+)"),
                    (None, Some(e)) => return format!("{path} (L1-L{e})"),
                    (None, None) => return path.to_string(),
                }
            }
        }
        "write" => {
            // Extract the destination path and include byte size for visibility into write volume.
            if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
                if let Some(content) = args.get("content").and_then(|v| v.as_str()) {
                    return format!("{path} ({} bytes)", content.len());
                }
                return path.to_string();
            }
        }
        "edit" => {
            // Edit targets are identified primarily by the target file being modified.
            if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
                return path.to_string();
            }
        }
        "bash" => {
            // Bash commands are bounded at 60 characters so long pipelines do not dominate context.
            // Newlines are sanitized to spaces to preserve single-line formatting in the action ledger.
            if let Some(cmd) = args.get("command").and_then(|v| v.as_str()) {
                let single_line = cmd.replace('\n', " ");
                if single_line.chars().count() > 60 {
                    let prefix: String = single_line.chars().take(57).collect();
                    return format!("{prefix}...");
                }
                return single_line;
            }
        }
        "glob" => {
            // Glob targets are represented by the file search pattern.
            if let Some(pattern) = args.get("pattern").and_then(|v| v.as_str()) {
                return pattern.to_string();
            }
        }
        "grep" => {
            // Grep targets represent the regex pattern and, when restricted, the target subtree.
            if let Some(pattern) = args.get("pattern").and_then(|v| v.as_str()) {
                if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
                    if !path.is_empty() {
                        return format!("pattern '{pattern}' in {path}");
                    }
                }
                return format!("pattern '{pattern}'");
            }
        }
        "blyte" => {
            if let Some(cmd) = format_blyte_tool_input(args) {
                return cmd;
            }
        }
        _ => {}
    }

    // Fallback: extract the first string argument value found, or default to the tool name.
    if let Some(obj) = args.as_object() {
        for val in obj.values() {
            if let Some(s) = val.as_str() {
                return s.to_string();
            }
        }
    }
    tool.to_string()
}

/// Extracts a one-line deterministic outcome summary from a tool execution result.
///
/// # Arguments
/// * `tool` - The name of the tool executed.
/// * `content` - Raw string output produced by the tool.
/// * `is_error` - Whether the tool execution resulted in an error status.
///
/// # Returns
/// A single-line summary string describing the outcome.
pub fn extract_action_summary(tool: &str, content: &str, is_error: bool) -> String {
    // Produce deterministic, bounded status summaries per tool category.
    match tool {
        "read" => {
            if is_error {
                let first = content
                    .lines()
                    .find(|l| !l.trim().is_empty())
                    .unwrap_or("read failed");
                let clamped: String = first.chars().take(80).collect();
                format!("failed: {clamped}")
            } else {
                // Count lines returned to indicate the volume read without including full content.
                let count = content.lines().count();
                format!("{count} lines read")
            }
        }
        "write" => {
            if is_error {
                let first = content
                    .lines()
                    .find(|l| !l.trim().is_empty())
                    .unwrap_or("write failed");
                let clamped: String = first.chars().take(80).collect();
                format!("failed: {clamped}")
            } else {
                // Static confirmation of file write completion.
                "file written".to_string()
            }
        }
        "edit" => {
            // Distinguish successful replacements from rejection/failure reasons.
            if is_error {
                let first = content
                    .lines()
                    .find(|l| !l.trim().is_empty())
                    .unwrap_or("edit failed");
                let clamped: String = first.chars().take(80).collect();
                format!("failed: {clamped}")
            } else {
                "string replaced".to_string()
            }
        }
        "bash" => {
            // Non-zero bash exits extract the terminal failure line to preserve diagnostics.
            if !is_error {
                "exit 0".to_string()
            } else {
                let last_line = content
                    .lines()
                    .rev()
                    .find(|l| !l.trim().is_empty())
                    .unwrap_or("command failed");
                let clamped: String = last_line.chars().take(80).collect();
                format!("failed: {clamped}")
            }
        }
        "glob" => {
            if is_error {
                let first = content
                    .lines()
                    .find(|l| !l.trim().is_empty())
                    .unwrap_or("glob failed");
                let clamped: String = first.chars().take(80).collect();
                format!("failed: {clamped}")
            } else {
                // Count matching file entries in the glob output.
                let count = content.lines().filter(|l| !l.trim().is_empty()).count();
                format!("{count} files matched")
            }
        }
        "grep" => {
            if is_error {
                let first = content
                    .lines()
                    .find(|l| !l.trim().is_empty())
                    .unwrap_or("grep failed");
                let clamped: String = first.chars().take(80).collect();
                format!("failed: {clamped}")
            } else {
                // Count matching occurrences found in content search.
                let count = content.lines().filter(|l| !l.trim().is_empty()).count();
                format!("{count} matches found")
            }
        }
        _ => {
            // Fallback for custom or unknown tools clamps the first line to 80 chars.
            let first = content.lines().next().unwrap_or("");
            first.chars().take(80).collect()
        }
    }
}