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
//! The native coding loop: plan → edit → verify → repair, on CAR inference.
//!
//! Shape mirrors `car-bench`'s `InferenceAgentRunner` (multi-turn tool-use
//! conversation) wrapped in `car-builder`'s repair-loop philosophy: each
//! iteration is a fresh conversation seeded with the intent plus the previous
//! iteration's failing check output, and the loop only exits green when
//! [`evaluate_contract`] — not the model — says so.
use std::sync::atomic::Ordering;
use async_trait::async_trait;
use car_engine::ToolExecutor;
use car_inference::tasks::generate::Message;
use car_inference::{GenerateParams, GenerateRequest, InferenceEngine, InferenceResult};
use serde_json::Value;
use super::contract::{evaluate_contract, CheckResult, OutcomeContract};
use super::session::{CancelFlag, CoderEventKind, EventSink};
use super::shell_tool::WorktreeExecutor;
use super::skill_memory::{FailureSignature, RepairMemory};
use crate::assistant::agent_loop::compact_history_to_window;
/// The model seam: one turn of generation. Implemented by
/// [`InferenceEngine`] for production; test harnesses script it (the same
/// injected-generation philosophy as `car-builder`).
#[async_trait]
pub trait TurnGenerator: Send + Sync {
async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String>;
/// The context window (in tokens) of the model this generator drives, or
/// `0` when unknown. Multi-turn drivers use it to bound their running
/// message history before it overflows the window. Defaults to `0` so
/// test doubles need not implement it (the loop then skips compaction).
fn context_window(&self, _model: &str) -> usize {
0
}
}
#[async_trait]
impl TurnGenerator for InferenceEngine {
async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String> {
self.generate_tracked(req).await.map_err(|e| e.to_string())
}
fn context_window(&self, model: &str) -> usize {
self.model_context_window(model)
}
}
/// The mid-session user-input seam: the loop hands a prompt to the host, which
/// surfaces it (emit `UserInputRequested`), blocks for the user's reply (while
/// respecting cancellation and a bound), and returns the text — or an `Err`
/// describing why no answer is coming (timeout, cancellation, no listener). An
/// `Err` is fed back to the model as a tool error so it can proceed without the
/// answer rather than the loop wedging.
///
/// Optional by design: when no asker is wired (most tests, the foreman/external
/// fallbacks), the `ask_user` tool is simply not offered to the model.
#[async_trait]
pub trait AskUser: Send + Sync {
async fn ask(&self, prompt: &str) -> Result<String, String>;
}
/// The name of the model-invokable mid-session question tool. Recognized by the
/// loop (not the `WorktreeExecutor`) so the channel plumbing stays with the
/// sink + cancel flag the loop already holds.
pub const ASK_USER_TOOL: &str = "ask_user";
/// How many times the SAME read-only call (tool + args) may repeat, with no
/// intervening mutating call, before the attempt is treated as a no-progress
/// thrash — the signature of a backbone that never returns its tool results, so
/// the model re-reads the same thing forever without ever acting on it. Surfaced
/// by dogfooding: a coder on a backbone that dropped tool history issued 210
/// identical `read_file` calls and zero edits before the turn cap. On a trip the
/// loop breaks to contract evaluation (earlier edits may already have passed);
/// only a second no-progress iteration aborts the session.
const NO_PROGRESS_REPEAT_LIMIT: u32 = 6;
/// Read-only coder tools — repeating one changes nothing, so a run of identical
/// read-only calls with no mutating call between them is the no-progress signal.
/// Anything not listed here (edit_file/write_file/shell/… and any external tool)
/// is treated as *progress* and clears the guard, so a legitimate read→edit or
/// build→edit→build loop never trips — the safe-by-default direction.
///
/// Known, accepted gap: a thrash driven through `shell` (e.g. `cat foo`/`ls`
/// every turn) is treated as progress and won't trip this guard — we can't tell
/// a read-only shell from a mutating one without a heuristic that would
/// re-introduce false positives on legitimate `shell` build/poll loops. Such a
/// thrash still degrades to the bounded `max_turns` terminal, not the silent
/// budget-burn. If ever worth closing, do it with a tool-agnostic backstop (an
/// iteration with zero successful *mutating* calls is no-progress) rather than
/// classifying shell command strings.
fn is_read_only_tool(name: &str) -> bool {
matches!(name, "read_file" | "list_dir" | "find_files" | "grep_files")
}
/// Tool definition for [`ASK_USER_TOOL`], appended to the model-visible tool
/// list only when an [`AskUser`] handler is wired.
fn ask_user_tool_def() -> Value {
serde_json::json!({
"name": ASK_USER_TOOL,
"description": "Ask the human user a question and wait for their reply. \
Use ONLY when you genuinely cannot proceed without a \
decision or missing fact the user alone can supply (an \
ambiguous requirement, a destructive choice, a missing \
credential). Do not use it for things you can determine \
by reading the repo or running commands. The call blocks \
until the user answers or a timeout elapses; on timeout \
you receive an error and should proceed with your best \
judgment.",
"parameters": {
"type": "object",
"properties": {
"prompt": {
"type": "string",
"description": "The question to show the user, phrased so a short reply answers it."
}
},
"required": ["prompt"]
}
})
}
/// Tuning for the native loop.
#[derive(Debug, Clone)]
pub struct NativeLoopConfig {
/// Pinned model id; `None` routes adaptively (TaskHint::Code).
pub model: Option<String>,
/// Contract-evaluation rounds before giving up.
pub max_iterations: u32,
/// Model turns within one iteration before forcing evaluation.
pub max_turns_per_iteration: u32,
/// Generation budget per turn.
pub max_tokens_per_turn: usize,
}
impl Default for NativeLoopConfig {
fn default() -> Self {
Self {
model: None,
max_iterations: 8,
max_turns_per_iteration: 24,
max_tokens_per_turn: 4096,
}
}
}
impl NativeLoopConfig {
/// Fold the general harness knobs the Evolution Agent tunes
/// ([`car_memgine::HarnessConfig`]) onto the coder's own budgets, so a
/// harness patch applied through `evolution.run`'s gated path actually
/// changes coder behavior. The coder's native loop does NOT read
/// `HarnessConfig` directly (it lives on the general `car_engine::Runtime`
/// executor), so without this an applied patch would be inert and the A/B
/// improvement loop could never converge. Mapping: `planning_max_replans`
/// (how many replan/repair rounds the runtime grants) → the coder's
/// `max_iterations` (contract-eval repair rounds); `max_retries` (per-action
/// retry budget) → a floor on `max_turns_per_iteration`. **Only ever RAISES
/// a budget** — a harness fix grants headroom; it never starves the coder
/// below its base config.
pub fn merge_harness(&mut self, h: &car_memgine::HarnessConfig) {
self.max_iterations = self
.max_iterations
.max(h.planning_max_replans.saturating_add(1));
self.max_turns_per_iteration = self.max_turns_per_iteration.max(h.max_retries);
}
}
/// How a loop run ended.
#[derive(Debug, Clone)]
pub struct LoopOutcome {
/// Every contract check passed.
pub passed: bool,
/// Iterations actually executed.
pub iterations: u32,
/// Check results from the final evaluation.
pub last_results: Vec<CheckResult>,
/// Terminal error (cancellation, repeated inference failure). `None` for
/// a clean pass OR a clean exhaustion of iterations.
pub error: Option<String>,
}
fn preview(s: &str, max: usize) -> String {
if s.len() <= max {
return s.to_string();
}
let mut end = max;
while !s.is_char_boundary(end) {
end -= 1;
}
format!("{}…", &s[..end])
}
fn system_prompt(contract: &OutcomeContract, environment: &str) -> String {
format!(
"You are CAR Coder, an autonomous coding agent working in an isolated git worktree \
of the user's repository. The worktree root is your working directory; all relative \
paths resolve against it.\n\n\
ENVIRONMENT:\n{environment}\n\n\
How to work:\n\
- Inspect before you edit. Read the relevant files and search the codebase \
(grep_files / find_files) to understand the code BEFORE changing it. Never \
fabricate file contents, symbols, or APIs you have not actually read.\n\
- Plan briefly, then make surgical edits: prefer edit_file for targeted changes \
over rewriting a whole file with write_file. Change the minimum the task needs.\n\
- Trace the checks before you declare done. Read each outcome-contract check and \
confirm your change actually makes it pass; watch common correctness pitfalls — \
preserve first-seen ORDER when de-duplicating (a bare set() loses order), match the \
EXACT expected values, and handle every symbol the checks exercise.\n\
- Verify your own work by running the EXACT command(s) from the OUTCOME CONTRACT \
below, verbatim — copy the command string character-for-character (same \
interpreter path, same flags, same scoped test file). Do NOT substitute a \
broader or 'equivalent' command: running `python -m pytest tests/` when the \
contract says `/path/to/venv/bin/python -m pytest -q tests/test_x.py` is WRONG \
— a different interpreter (e.g. a system `python` that is a different version \
with different installed packages) can fail on environment issues that have \
nothing to do with your task. Read that command's real output before declaring \
done; the contract's exact command is the only thing that decides done. Never \
claim a check passed without having run its exact command this session and seen \
it pass.\n\
- NEVER repair, reconfigure, or work around the environment. This is a hard rule. \
If the contract's exact command errors on something that is not your code — an \
interpreter/Python version mismatch, a missing or incompatible package, an \
import error in unrelated modules, a broken test runner — that is NOT your task \
and NOT something you fix. You are STRICTLY FORBIDDEN from: running `pip install` \
/ `pip uninstall` / any package-manager mutation; writing, editing, or deleting \
`sitecustomize.py`, `conftest.py`, `UserDict.py`, `tox.ini`, `pyproject.toml`, \
`setup.cfg`, or any interpreter/test-runner shim or config to change how tests \
run; switching interpreters, creating venvs, or setting PYTHONPATH tricks. If \
your ONLY remaining failures are environment failures like these, your CODE fix \
is already done: write your summary and STOP. The runtime re-runs the contract \
in the correct environment to decide done — do not burn turns trying to make a \
wrong-environment command pass.\n\
- If the shell tool is unavailable or a command is blocked this session (e.g. a \
permission-restricted runner returns an approval error instead of output), that \
is NOT a task failure and NOT a reason to report the work as blocked or uncertain: \
the runtime independently runs the outcome contract to decide done. Make your edits \
correct, note that you could not self-run the checks, and STOP — do not retry the \
blocked command in a loop.\n\
- On failure, read the actual error output before retrying — fix the specific \
cause the compiler or test named; do not guess-and-retry. If the error names a \
missing symbol, function, or attribute, IMPLEMENT it rather than editing the \
caller. If the same check fails again after an edit, your hypothesis was wrong: \
re-read the exact expected-vs-actual and form a different one — do not re-apply a \
variation of an edit that did not change the failure.\n\n\
Policy:\n\
- Policy denies git push, sudo, and destructive operations outside the worktree — \
do not attempt them.\n\
- Do not git commit; the runtime handles version control.\n\n\
When you believe the work is complete, reply with a brief plain-text summary and \
STOP calling tools. The runtime independently re-runs the outcome contract after \
you stop — but do not rely on it: verify the checks yourself first, because a red \
re-invocation costs a full round-trip.\n\n\
OUTCOME CONTRACT (the runtime runs these to decide done):\n{}",
contract.render()
)
}
/// Feedback injected as a new user turn on a red repair round. `same_failure_streak`
/// is how many prior consecutive rounds the SAME primary check has failed (0 on the
/// first failure or when the failing check just changed). It escalates the repair
/// discipline: on a fresh failure, direct the model to read the specific error and
/// fix the named cause; on a recurring one, tell it its approach isn't working so it
/// stops re-applying a variation of a non-converging edit. Surfaced by the coder A/B
/// on hard real-codebase tasks, where the coder edited 20+ times across 6 rounds but
/// never addressed the actual cause (a missing function the test named).
fn failure_feedback(results: &[CheckResult], same_failure_streak: u32) -> String {
let mut msg = String::from(
"The outcome contract was evaluated and some checks FAILED. Fix the code so they pass.\n\n",
);
for r in results.iter().filter(|r| !r.passed) {
msg.push_str(&format!(
"FAILED {} (exit {:?}):\n{}\n\n",
r.name, r.exit_code, r.output_tail
));
}
if same_failure_streak == 0 {
msg.push_str(
"Before editing again: read the SPECIFIC failure above — the exact assertion, error \
type, or traceback line — and name the single cause. If the error names a missing \
symbol/function/attribute, implement THAT symbol. Find the code responsible for the \
named cause and fix it directly; do not guess-and-retry.\n",
);
} else {
msg.push_str(&format!(
"This check has now failed {} times in a row despite your edits — your approach is NOT \
addressing the real cause, so do NOT re-apply a variation of the same edit. STOP and \
read the failure literally: what exact value or behavior was EXPECTED vs what was \
PRODUCED? Trace that exact value back to the specific code that produces it, form a \
DIFFERENT hypothesis about the named cause, and make one targeted change to it. If the \
error names a missing symbol/function/attribute, the fix is to IMPLEMENT it, not to \
adjust the caller.\n",
same_failure_streak + 1
));
}
msg
}
/// The signature of the most-relevant failure in a red evaluation: the first
/// failing check. One signature per repair round keeps learning attributable.
fn primary_failure(results: &[CheckResult]) -> Option<FailureSignature> {
results
.iter()
.find(|r| !r.passed)
.map(FailureSignature::from_check)
}
/// Append a recalled repair hint to the repair prompt. Kept terse and clearly
/// labelled as a heuristic from a prior session so the model treats it as a
/// lead, not gospel.
fn append_recall_hint(prompt: &mut String, hint: &str) {
prompt.push_str(
"\nHINT — a prior session resolved this same failure signature with this approach; \
use it as a lead, verify it still applies:\n",
);
prompt.push_str(hint);
prompt.push('\n');
}
fn message_memory_text(message: &Message) -> Option<String> {
match message {
Message::System { content }
| Message::User { content }
| Message::Assistant { content, .. }
| Message::ToolResult { content, .. } => {
let trimmed = content.trim();
(!trimmed.is_empty()).then(|| trimmed.to_string())
}
Message::UserMultimodal { content } => {
let text = content
.iter()
.filter_map(|block| match block {
car_inference::ContentBlock::Text { text } => Some(text.trim()),
_ => None,
})
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join("\n");
(!text.is_empty()).then_some(text)
}
_ => None,
}
}
fn append_context_block(req: &mut GenerateRequest, title: &str, body: &str) {
let block = format!("## {title}\n{body}");
req.context = Some(match req.context.take() {
Some(existing) if !existing.trim().is_empty() => format!("{existing}\n\n{block}"),
_ => block,
});
}
async fn maybe_apply_coder_proactive_memory(
req: &mut GenerateRequest,
intent: &str,
messages: &[Message],
sink: &EventSink,
memory: &RepairMemory,
) {
let mut recent = messages
.iter()
.rev()
.filter_map(message_memory_text)
.take(6)
.collect::<Vec<_>>();
recent.reverse();
let events = sink.events();
let Some((maintenance, decision)) = memory.proactive_for_task(intent, recent, &events).await
else {
return;
};
sink.record_proactive_memory(&maintenance, &decision);
if let car_memgine::ProactiveMemoryDecision::Inject { reminder, .. } = decision {
append_context_block(req, "Proactive Memory", &reminder);
}
}
/// Distill a durable, reusable approach summary from the iteration that turned
/// the contract green. The model's closing plan text (its own summary of what
/// it did) is the best signal; fall back to a generic marker when it stayed
/// silent so the skill still records that *something* fixed this signature.
fn winning_approach(sig: &FailureSignature, plan_text: &str) -> String {
let plan = plan_text.trim();
if plan.is_empty() {
format!(
"Re-attempted the edit; the '{}' failure of check '{}' cleared after repair.",
sig.error_class, sig.check
)
} else {
preview(plan, 1024)
}
}
/// Drive the native loop to completion, cancellation, or exhaustion.
///
/// When `ask` is `Some`, the model is additionally offered the [`ASK_USER_TOOL`]
/// to request mid-session input; the loop routes that one tool to the handler
/// (not the worktree executor) so a question blocks on the user-input gate while
/// honoring cancellation and the gate's timeout.
#[allow(clippy::too_many_arguments)]
pub async fn run_native_loop(
inference: &dyn TurnGenerator,
executor: &WorktreeExecutor,
intent: &str,
contract: &OutcomeContract,
sink: &EventSink,
cancel: &CancelFlag,
cfg: &NativeLoopConfig,
memory: &RepairMemory,
ask: Option<&dyn AskUser>,
) -> LoopOutcome {
let mut tools = WorktreeExecutor::tool_defs();
if ask.is_some() {
tools.push(ask_user_tool_def());
}
// ENVIRONMENT section (F7/L1): reuse the same cheap names-only repo summary
// the contract-derivation prompt uses, so the coding loop and contract
// derivation describe the repo identically. Local worktree by construction.
let environment = super::rpc::summarize_repo(executor.worktree());
let system = system_prompt(contract, &environment);
let mut feedback: Option<String> = None;
let mut last_results: Vec<CheckResult> = Vec::new();
let mut consecutive_inference_failures = 0u32;
// Consecutive repair iterations that ended in a no-progress thrash. The
// conversation persists across rounds, so a genuinely wedged backbone
// re-thrashes identically; abort on the second such iteration.
let mut no_progress_iterations = 0u32;
// The primary failing check from the previous red round + how many rounds it
// has recurred, so the repair feedback escalates when the coder's edits keep
// failing the SAME check (not converging on hard tasks).
let mut prev_primary_check: Option<String> = None;
let mut same_failure_streak = 0u32;
// The signature of the failure carried into THIS iteration's repair, if
// any. Drives skill recall (inject a prior fix) and outcome attribution
// (credit/penalize that signature's skill once we know if the repair held).
let mut prior_sig: Option<FailureSignature> = None;
// Persist ONE conversation across repair iterations (F2, audit 2026-07-06):
// the model keeps the files it read, the edits it made, and the dead-ends it
// already ruled out. A failed contract appends its feedback as a new user
// turn on this thread rather than resetting to [System, User] every round —
// so each repair builds on accumulated understanding instead of re-deriving
// the repo from scratch. The thread is bounded to the model's context window
// each turn (`compact_history_to_window` below) so a long repair session
// can't overflow it.
// Session-start recall (F8-lite/L3): a ONE-TIME, task-scoped heuristic lead
// from prior sessions, computed once (one short lock) and injected into the
// persistent first user turn. Distinct from the per-repair-round recall hint
// below, which is failure-signature-scoped. `None` when learning is disabled
// or nothing overlaps the intent → nothing is injected (no empty section).
let mut initial_user = format!("Task:\n{intent}\n");
if let Some(block) = memory.recall_for_task(intent).await {
initial_user.push_str(
"\nRecall from prior sessions (heuristic — verify against the repo \
before acting on it):\n",
);
initial_user.push_str(&block);
}
let mut messages = vec![
Message::System {
content: system.clone(),
},
Message::User {
content: initial_user,
},
];
// The model's context window, resolved once (the model is fixed for the
// run). Bounds the persistent conversation each turn; 0 (unknown — e.g. a
// local/test generator) disables compaction, so behavior is unchanged there.
let context_window = cfg
.model
.as_deref()
.map(|m| inference.context_window(m))
.unwrap_or(0);
for iteration in 1..=cfg.max_iterations {
if cancel.load(Ordering::SeqCst) {
return LoopOutcome {
passed: false,
iterations: iteration - 1,
last_results,
error: Some("cancelled".into()),
};
}
sink.emit(CoderEventKind::IterationStarted {
n: iteration,
max: cfg.max_iterations,
});
// On a repair iteration, append the failing-check feedback (plus any
// recalled prior-session fix for this failure signature) as a NEW user
// turn on the persistent thread. Iteration 1 has no feedback — the task
// seed above is the only user turn.
if let Some(fb) = &feedback {
let mut user = fb.clone();
// Durable recall: if a prior session learned a fix for this failure
// signature, inject it as a lead. No-op when learning is disabled or
// nothing matches.
if let Some(sig) = &prior_sig {
if let Some(hint) = memory.recall(sig).await {
append_recall_hint(&mut user, &hint);
}
}
messages.push(Message::User { content: user });
}
// The model's closing summary for this iteration — captured to distill
// a durable repair skill if this iteration turns the contract green.
let mut closing_plan = String::new();
// Inner tool-use conversation.
let mut turn = 0;
// No-progress guard (per iteration): counts identical READ-ONLY calls
// since the last mutating call, so a thrashing model (re-reading the same
// thing with no edits) is caught. Cleared by any mutating call (progress)
// and reset per iteration. `no_progress_this_iteration` records a trip so
// the turn loop breaks to contract evaluation.
let mut identical_read_calls: std::collections::HashMap<(String, String), u32> =
std::collections::HashMap::new();
let mut no_progress_this_iteration = false;
// Journal the iteration's terminal decision for the harness miners: the
// model declaring done (empty tool calls — possibly a truncated/starved
// turn on a local model) vs. exhausting the per-iteration turn budget
// (the coder-path "never finishes" signal). `last_model` attributes it.
let mut last_model = String::new();
let mut model_declared_done = false;
while turn < cfg.max_turns_per_iteration {
turn += 1;
if cancel.load(Ordering::SeqCst) {
return LoopOutcome {
passed: false,
iterations: iteration,
last_results,
error: Some("cancelled".into()),
};
}
// Bound the persistent conversation to the model's context window
// before each generate so a long repair session never overflows it —
// an overflow head-truncates the System prompt (outcome contract) +
// task provider-side on a small local model, the exact silent failure
// this loop must avoid. Pins System + task, drops oldest middle turns
// on a valid turn boundary; no-op when the window is unknown or fits.
compact_history_to_window(&mut messages, context_window);
let mut req = GenerateRequest {
prompt: intent.to_string(), // ignored when messages are set
model: cfg.model.clone(),
params: GenerateParams {
temperature: 0.0,
max_tokens: cfg.max_tokens_per_turn,
..Default::default()
},
tools: Some(tools.clone()),
messages: Some(messages.clone()),
intent: Some(car_inference::IntentHint {
task: Some(car_inference::TaskHint::Code),
// Stakes-aware routing: this loop edits and runs code in a
// real git worktree and can drive a merge — structurally
// irreversible, so it is UNCONDITIONALLY high-stakes (unlike
// a general planner, the coder can never be benign — its
// tools are write_file/run_command). Generate with the best
// model; cost is the wrong axis when a wrong edit lands in a
// real repo. No-op when `cfg.model` pins an explicit model
// (the router consults intent only on the unpinned arm).
high_stakes: true,
..Default::default()
}),
..Default::default()
};
maybe_apply_coder_proactive_memory(&mut req, intent, &messages, sink, memory).await;
let result = match inference.generate(req).await {
Ok(r) => {
consecutive_inference_failures = 0;
r
}
Err(e) => {
consecutive_inference_failures += 1;
sink.emit(CoderEventKind::Error {
message: format!("inference failed (turn {turn}): {e}"),
});
if consecutive_inference_failures >= 3 {
return LoopOutcome {
passed: false,
iterations: iteration,
last_results,
error: Some(format!("inference failed repeatedly: {e}")),
};
}
continue; // retry the same turn
}
};
last_model = result.model_used.clone();
if result.tool_calls.is_empty() {
// A turn that hit the max_tokens ceiling is CUT OFF, not a
// completion — treating it as "done" silently accepts a
// truncated answer (and, on a truncated tool call, would drop
// the call entirely). Recognize the truncation and continue so
// the model can finish where it left off. Bounded by
// max_turns_per_iteration, so this cannot spin forever — and if
// the model truncates every turn, the turn-budget terminal
// below journals that exhaustion as the mineable failure.
// (F3/F11, audit 2026-07-06.)
if result.was_truncated() {
sink.emit(CoderEventKind::Error {
message: format!(
"model turn truncated (stop_reason={:?}) — continuing so it can finish",
result.stop_reason
),
});
messages.push(Message::Assistant {
content: result.text.clone(),
tool_calls: vec![],
thinking: result.thinking.clone(),
});
messages.push(Message::User {
content: "Your previous response was cut off at the token limit. \
Continue exactly where you left off; if you were in the \
middle of a tool call, re-issue that call in full."
.to_string(),
});
continue;
}
// Model says done — break to contract evaluation. Journal the
// terminal so the finish is mineable; with the truncation guard
// above, reaching here means a genuine (non-truncated) finish
// (docs/audits/car-tracing-design-2026-07-07, native_loop:344).
sink.record_turn_completed(
"empty_tool_calls",
result.stop_reason.as_deref(),
result.was_truncated(),
turn,
&result.model_used,
);
model_declared_done = true;
if !result.text.trim().is_empty() {
closing_plan = result.text.clone();
sink.emit(CoderEventKind::PlanText {
text: result.text.clone(),
});
}
break;
}
// Assign ids so ToolResult replies correlate (local models may
// omit them), then execute sequentially in emitted order.
let mut calls = result.tool_calls.clone();
for (i, call) in calls.iter_mut().enumerate() {
if call.id.is_none() {
call.id = Some(format!("call_{iteration}_{turn}_{i}"));
}
}
messages.push(Message::Assistant {
content: result.text.clone(),
tool_calls: calls.clone(),
thinking: result.thinking.clone(), // preserve for next-turn replay (F1)
});
for call in &calls {
let params = Value::Object(call.arguments.clone().into_iter().collect());
sink.emit(CoderEventKind::ToolCall {
tool: call.name.clone(),
params_preview: preview(¶ms.to_string(), 400),
});
// No-progress guard. A repeated read-only call (same tool+args)
// with no editing/mutating call in between means the model is
// thrashing — re-reading the same thing every turn without acting
// on it (the signature of a backbone that never returns its tool
// results). Any mutating call (edit/write/shell/…) is *progress*
// and clears the tracker, so a legitimate read→edit→re-read or a
// build→edit→build loop never trips. On a trip we DON'T fail the
// session outright — we break to contract evaluation so earlier
// edits that already satisfied the contract still pass; only a
// second no-progress iteration (a genuinely wedged backbone, since
// the conversation persists across repair rounds) aborts.
if is_read_only_tool(&call.name) {
let c = identical_read_calls
.entry((call.name.clone(), params.to_string()))
.or_insert(0);
*c += 1;
if *c >= NO_PROGRESS_REPEAT_LIMIT && !no_progress_this_iteration {
no_progress_this_iteration = true;
sink.emit(CoderEventKind::Error {
message: format!(
"no-progress loop: `{}` called {c} times with identical arguments \
and no intervening edit — ending this attempt",
call.name
),
});
}
} else {
// A mutating/acting call — progress. Forget the read history.
identical_read_calls.clear();
}
let (ok, content) = if call.name == ASK_USER_TOOL {
// Route to the user-input handler, not the worktree executor.
// The handler emits UserInputRequested, blocks on the gate
// (honoring cancel + timeout), and returns the user's text or
// an error the model can recover from.
match ask {
Some(asker) => {
let prompt = params
.get("prompt")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
match asker.ask(&prompt).await {
Ok(answer) => (true, answer),
Err(e) => (false, format!("ERROR: {e}")),
}
}
None => (
false,
"ERROR: ask_user is not available in this session".to_string(),
),
}
} else {
match executor.execute(&call.name, ¶ms).await {
Ok(v) => (true, v.to_string()),
Err(e) => (false, format!("ERROR: {e}")),
}
};
sink.emit(CoderEventKind::ToolResult {
tool: call.name.clone(),
ok,
preview: preview(&content, 400),
});
messages.push(Message::ToolResult {
tool_use_id: call.id.clone().expect("assigned above"),
content: preview(&content, 16 * 1024),
});
}
// A no-progress trip ends this attempt: stop taking turns and let the
// contract decide (earlier edits may already have satisfied it).
if no_progress_this_iteration {
break;
}
}
// Journal the inner loop's terminal (the contract, evaluated next, still
// owns the pass/fail decision): a no-progress bail-out, or the "never
// finishes" turn-budget exhaustion, vs. a genuine model-declared done.
if no_progress_this_iteration {
sink.record_turn_completed("no_progress_loop", None, false, turn, &last_model);
} else if !model_declared_done {
sink.record_turn_completed("max_turns", None, false, turn, &last_model);
}
// Verify. The contract — not the model's self-report — decides.
last_results = evaluate_contract(contract, executor, sink).await;
if last_results.iter().all(|r| r.passed) {
// Durable learning: if THIS green came after a prior failure, the
// repair held — credit (or ingest) the skill for that signature so
// the next occurrence can recall the winning approach.
if let Some(sig) = &prior_sig {
memory
.record_success(sig, &winning_approach(sig, &closing_plan))
.await;
}
return LoopOutcome {
passed: true,
iterations: iteration,
last_results,
error: None,
};
}
// Still red. If this iteration made no progress (a read-only thrash) and
// the contract didn't pass, count it — a second consecutive no-progress
// iteration means the backbone is wedged (it re-thrashes the persistent
// conversation identically), so abort rather than burn every iteration.
// A productive iteration resets the count.
if no_progress_this_iteration {
no_progress_iterations += 1;
if no_progress_iterations >= 2 {
return LoopOutcome {
passed: false,
iterations: iteration,
last_results,
error: Some(
"no-progress loop: the model repeatedly re-read the same files without \
making edits across two attempts — the backbone is likely not returning \
tool results. Aborted before exhausting the iteration budget."
.to_string(),
),
};
}
} else {
no_progress_iterations = 0;
}
// Track whether the SAME primary check keeps failing, so the repair
// feedback escalates from "read the error" to "your approach isn't
// working — form a different hypothesis" when the coder isn't converging.
let cur_primary_check = last_results
.iter()
.find(|r| !r.passed)
.map(|r| r.name.clone());
if cur_primary_check.is_some() && cur_primary_check == prev_primary_check {
same_failure_streak += 1;
} else {
same_failure_streak = 0;
}
prev_primary_check = cur_primary_check;
// Record the failure against its signature (penalizing any recalled
// approach that didn't hold) and carry it into the next repair round for
// recall + attribution.
feedback = Some(failure_feedback(&last_results, same_failure_streak));
if let Some(sig) = primary_failure(&last_results) {
memory.record_failure(&sig).await;
prior_sig = Some(sig);
} else {
prior_sig = None;
}
}
LoopOutcome {
passed: false,
iterations: cfg.max_iterations,
last_results,
error: None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::coder::contract::ContractCheck;
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
#[test]
fn merge_harness_raises_coder_budgets_only_upward() {
// A harness patch that raised planning_max_replans should raise the
// coder's repair rounds; a lower/default knob must never lower them.
let mut cfg = NativeLoopConfig {
max_iterations: 8,
max_turns_per_iteration: 24,
..Default::default()
};
cfg.merge_harness(&car_memgine::HarnessConfig {
max_retries: 30,
retry_backoff_ms: 0,
planning_max_replans: 12, // > base 8 → raises to 13
});
assert_eq!(
cfg.max_iterations, 13,
"planning_max_replans+1 reaches the coder"
);
assert_eq!(
cfg.max_turns_per_iteration, 30,
"max_retries raises the turn floor"
);
// A default (small) harness config never starves the coder below base.
let mut base = NativeLoopConfig {
max_iterations: 8,
max_turns_per_iteration: 24,
..Default::default()
};
base.merge_harness(&car_memgine::HarnessConfig::default()); // {3,0,2}
assert_eq!(base.max_iterations, 8, "never lowered below base");
assert_eq!(base.max_turns_per_iteration, 24);
}
/// Scripted generator: pops pre-canned turns in order.
struct Script {
turns: Vec<InferenceResult>,
cursor: AtomicUsize,
}
fn turn(text: &str, tool_calls: serde_json::Value) -> InferenceResult {
serde_json::from_value(serde_json::json!({
"text": text,
"tool_calls": tool_calls,
"trace_id": "t",
"model_used": "scripted",
"latency_ms": 0,
}))
.expect("scripted InferenceResult shape")
}
fn turn_with_stop(
text: &str,
tool_calls: serde_json::Value,
stop_reason: Option<&str>,
) -> InferenceResult {
serde_json::from_value(serde_json::json!({
"text": text,
"tool_calls": tool_calls,
"trace_id": "t",
"model_used": "scripted",
"latency_ms": 0,
"stop_reason": stop_reason,
}))
.expect("scripted InferenceResult shape")
}
#[async_trait]
impl TurnGenerator for Script {
async fn generate(&self, _req: GenerateRequest) -> Result<InferenceResult, String> {
let i = self.cursor.fetch_add(1, Ordering::SeqCst);
self.turns
.get(i)
.cloned()
.ok_or_else(|| "script exhausted".to_string())
}
}
#[tokio::test]
async fn scripted_loop_edits_verifies_and_passes() {
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let (sink, collected) = EventSink::collecting("coder-native");
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
// Turn 1: write the file. Turn 2: declare done (no tool calls).
let script = Script {
turns: vec![
turn(
"creating the file",
serde_json::json!([{
"id": "c1",
"name": "write_file",
"arguments": {"path": "hello.txt", "content": "hello coder"}
}]),
),
turn("done — file created", serde_json::json!([])),
],
cursor: AtomicUsize::new(0),
};
let contract = OutcomeContract {
description: "hello.txt exists with content".into(),
checks: vec![ContractCheck {
name: "exists".into(),
command: crate::coder::test_cmds::contains("coder", "hello.txt"),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 10,
}],
};
let outcome = run_native_loop(
&script,
&executor,
"create hello.txt containing 'hello coder'",
&contract,
&sink,
&cancel,
&NativeLoopConfig::default(),
&RepairMemory::disabled(),
None,
)
.await;
assert!(outcome.passed, "outcome: {outcome:?}");
assert_eq!(outcome.iterations, 1);
assert!(dir.path().join("hello.txt").exists());
// Event stream shape: iteration → tool call/result → plan → check.
let events = collected.lock().unwrap();
let types: Vec<&str> = events
.iter()
.map(|e| match &e.kind {
CoderEventKind::IterationStarted { .. } => "iteration",
CoderEventKind::ToolCall { .. } => "tool_call",
CoderEventKind::ToolResult { .. } => "tool_result",
CoderEventKind::PlanText { .. } => "plan",
CoderEventKind::CheckStarted { .. } => "check_started",
CoderEventKind::CheckCompleted { .. } => "check_completed",
_ => "other",
})
.collect();
assert_eq!(
types,
vec![
"iteration",
"tool_call",
"tool_result",
"plan",
"check_started",
"check_completed"
]
);
}
// Identical read_file every turn — the thrash a backbone that drops tool
// history induces (re-read forever, never edit, never declare done).
fn identical_read_turn() -> InferenceResult {
turn(
"reading again",
serde_json::json!([{
"id": "c",
"name": "read_file",
"arguments": {"path": "src.py"}
}]),
)
}
#[tokio::test]
async fn native_loop_no_progress_bails_but_green_contract_still_passes() {
// A no-progress trip must NOT fail a session whose earlier state already
// satisfies the contract — the guard breaks to contract evaluation, and a
// green contract wins. (Regression guard against reporting green as failed.)
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let (sink, _collected) = EventSink::collecting("coder-native");
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let script = Script {
turns: (0..NO_PROGRESS_REPEAT_LIMIT + 2)
.map(|_| identical_read_turn())
.collect(),
cursor: AtomicUsize::new(0),
};
// Always-green contract.
let contract = OutcomeContract {
description: "already satisfied".into(),
checks: vec![ContractCheck {
name: "ok".into(),
// Portable `exit 0` — a bare `true` is a POSIX builtin and runs
// through the coder's shell (`cmd /C` on Windows), where it is
// not a command, so the "always-green" contract came back red.
command: crate::coder::test_cmds::PASS.into(),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 10,
}],
};
let outcome = run_native_loop(
&script,
&executor,
"fix the bug",
&contract,
&sink,
&cancel,
&NativeLoopConfig::default(),
&RepairMemory::disabled(),
None,
)
.await;
assert!(
outcome.passed,
"green contract must pass despite the thrash: {outcome:?}"
);
assert_eq!(outcome.iterations, 1);
}
#[tokio::test]
async fn native_loop_aborts_after_two_no_progress_iterations() {
// A genuinely wedged backbone re-thrashes the persistent conversation every
// repair round; after the second no-progress iteration (contract still red)
// the session aborts with a diagnostic instead of burning every iteration.
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let (sink, _collected) = EventSink::collecting("coder-native");
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
// Enough identical turns for two iterations to each trip the guard.
let script = Script {
turns: (0..(NO_PROGRESS_REPEAT_LIMIT * 2 + 4))
.map(|_| identical_read_turn())
.collect(),
cursor: AtomicUsize::new(0),
};
// Always-red contract, so each no-progress iteration stays failed.
let contract = OutcomeContract {
description: "never satisfied".into(),
checks: vec![ContractCheck {
name: "never".into(),
command: crate::coder::test_cmds::FAIL.to_string(),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 10,
}],
};
let outcome = run_native_loop(
&script,
&executor,
"fix the bug",
&contract,
&sink,
&cancel,
&NativeLoopConfig::default(),
&RepairMemory::disabled(),
None,
)
.await;
assert!(!outcome.passed, "outcome: {outcome:?}");
let err = outcome.error.unwrap_or_default();
assert!(err.contains("no-progress loop"), "error was: {err}");
// Aborted on the second iteration — not left to run all 8.
assert_eq!(outcome.iterations, 2);
}
#[tokio::test]
async fn native_loop_empty_tool_calls_journals_turn_completed() {
// The empty-tool-calls "model says done" terminal must record a durable
// TurnCompleted so a truncated/starved local "done" is mineable as
// false-success rather than passing silently as a clean finish.
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let journal = dir.path().join("events.jsonl");
// A journaled sink (record_turn_completed is journal-only — a collecting
// sink has no journal, so it would be a no-op there).
let sink = EventSink::new("coder-native", None, Some(journal.clone()));
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let script = Script {
turns: vec![
turn(
"creating the file",
serde_json::json!([{
"id": "c1",
"name": "write_file",
"arguments": {"path": "hello.txt", "content": "hello coder"}
}]),
),
turn("done — file created", serde_json::json!([])),
],
cursor: AtomicUsize::new(0),
};
let contract = OutcomeContract {
description: "hello.txt exists with content".into(),
checks: vec![ContractCheck {
name: "exists".into(),
command: crate::coder::test_cmds::contains("coder", "hello.txt"),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 10,
}],
};
let outcome = run_native_loop(
&script,
&executor,
"create hello.txt containing 'hello coder'",
&contract,
&sink,
&cancel,
&NativeLoopConfig::default(),
&RepairMemory::disabled(),
None,
)
.await;
assert!(outcome.passed, "outcome: {outcome:?}");
// Drop the sink to join the journal writer thread (flush), then reload.
drop(sink);
let log = car_eventlog::EventLog::load(&journal).unwrap();
let terminals: Vec<_> = log
.events()
.iter()
.filter(|e| e.kind == car_eventlog::EventKind::TurnCompleted)
.collect();
assert_eq!(
terminals.len(),
1,
"exactly one empty-tool-calls terminal recorded"
);
let ev = terminals[0];
assert_eq!(
ev.data.get("decision"),
Some(&serde_json::json!("empty_tool_calls"))
);
assert_eq!(
ev.data.get("model_id"),
Some(&serde_json::json!("scripted"))
);
// "scripted" carries no provider prefix in the allow-list → unknown tier
// (a real local run would surface e.g. "mlx/...": local).
assert_eq!(
ev.data.get("model_tier"),
Some(&serde_json::json!("unknown"))
);
}
#[tokio::test]
async fn native_loop_injects_proactive_memory_from_journaled_failures() {
use car_memgine::MemgineEngine;
use std::sync::Mutex as StdMutex;
use tokio::sync::Mutex as AsyncMutex;
struct CaptureContext {
seen: Arc<StdMutex<Vec<Option<String>>>>,
}
#[async_trait]
impl TurnGenerator for CaptureContext {
async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String> {
self.seen.lock().unwrap().push(req.context.clone());
Ok(turn("done", serde_json::json!([])))
}
}
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let journal = dir.path().join("events.jsonl");
let sink = EventSink::new("coder-native", None, Some(journal.clone()));
sink.emit(CoderEventKind::ToolResult {
tool: "shell".into(),
ok: false,
preview: "pytest failed because fixture data is missing".into(),
});
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let memory = RepairMemory::new(Some(Arc::new(AsyncMutex::new(MemgineEngine::new(None)))));
let seen = Arc::new(StdMutex::new(Vec::new()));
let capture = CaptureContext { seen: seen.clone() };
let contract = OutcomeContract {
description: "noop".into(),
checks: vec![],
};
let outcome = run_native_loop(
&capture,
&executor,
"fix the pytest failure",
&contract,
&sink,
&cancel,
&NativeLoopConfig::default(),
&memory,
None,
)
.await;
assert!(outcome.passed, "outcome: {outcome:?}");
let contexts = seen.lock().unwrap();
let context = contexts[0].as_deref().unwrap_or("");
assert!(
context.contains("## Proactive Memory"),
"request context should carry proactive memory: {context}"
);
assert!(
context.contains("Action shell in proposal session failed"),
"journaled failure should be injected: {context}"
);
drop(sink);
let log = car_eventlog::EventLog::load(&journal).unwrap();
assert!(log
.events()
.iter()
.any(|e| e.kind == car_eventlog::EventKind::ProactiveMemoryMaintained));
assert!(log.events().iter().any(|e| {
e.kind == car_eventlog::EventKind::ProactiveMemoryIntervention
&& e.data.get("decision") == Some(&serde_json::json!("inject"))
}));
}
#[tokio::test]
async fn native_loop_turn_budget_exhaustion_journals_max_turns() {
// The model never declares done — it keeps issuing tool calls until the
// per-iteration turn budget is exhausted. That "never finishes" terminal
// must be journaled as a max_turns TurnCompleted (the coder path has no
// stall guard, so this is the only signal that the budget burned out).
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let journal = dir.path().join("events.jsonl");
let sink = EventSink::new("coder-native", None, Some(journal.clone()));
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let tool_turn = || {
turn(
"still working",
serde_json::json!([{
"id": "c",
"name": "write_file",
"arguments": {"path": "scratch.txt", "content": "x"}
}]),
)
};
let script = Script {
turns: vec![tool_turn(), tool_turn()],
cursor: AtomicUsize::new(0),
};
let contract = OutcomeContract {
description: "never satisfied".into(),
checks: vec![ContractCheck {
name: "exists".into(),
command: crate::coder::test_cmds::contains("coder", "hello.txt"),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 10,
}],
};
let cfg = NativeLoopConfig {
model: None,
max_iterations: 1,
max_turns_per_iteration: 2,
max_tokens_per_turn: 4096,
};
let outcome = run_native_loop(
&script,
&executor,
"keep writing forever",
&contract,
&sink,
&cancel,
&cfg,
&RepairMemory::disabled(),
None,
)
.await;
assert!(!outcome.passed, "outcome: {outcome:?}");
drop(sink);
let log = car_eventlog::EventLog::load(&journal).unwrap();
let max_turns: Vec<_> = log
.events()
.iter()
.filter(|e| {
e.kind == car_eventlog::EventKind::TurnCompleted
&& e.data.get("decision") == Some(&serde_json::json!("max_turns"))
})
.collect();
assert_eq!(
max_turns.len(),
1,
"turn-budget exhaustion recorded once as max_turns"
);
assert_eq!(max_turns[0].data.get("turns"), Some(&serde_json::json!(2)));
}
#[tokio::test]
async fn native_loop_compacts_persistent_history_to_context_window() {
// F2 persists ONE conversation across repair turns; without bounding it to
// the model's context window, a long run overflows and head-truncates the
// System prompt (outcome contract) + task provider-side on a small local
// model — the exact silent failure this loop must avoid. Assert the loop
// calls compaction each turn: with a tiny window and large turns, the
// history the generator sees stays bounded (does NOT accumulate one
// exchange per turn) and always keeps the System prompt pinned at the head.
use std::sync::Mutex;
struct RecordingGen {
// (message count, starts-with-System) observed on each generate.
seen: Arc<Mutex<Vec<(usize, bool)>>>,
// Distinct call per turn so the (legitimate) no-progress guard, which
// aborts on identical repeats, doesn't fire before all 12 turns run.
turn_no: AtomicUsize,
}
#[async_trait]
impl TurnGenerator for RecordingGen {
async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String> {
let msgs = req.messages.as_ref().expect("coder always sets messages");
let starts_with_system = matches!(msgs.first(), Some(Message::System { .. }));
self.seen
.lock()
.unwrap()
.push((msgs.len(), starts_with_system));
// A large assistant turn + a DISTINCT tool call every turn so the
// persistent thread would grow unbounded absent compaction, and the
// model never declares done (the contract below never passes).
let n = self.turn_no.fetch_add(1, Ordering::SeqCst);
Ok(turn(
&"x".repeat(8000),
serde_json::json!([{
"id": format!("c{n}"),
"name": "write_file",
"arguments": {"path": format!("big{n}.txt"), "content": "y"}
}]),
))
}
fn context_window(&self, _model: &str) -> usize {
200 // tiny: budget = 150 tokens, far below one 8KB assistant turn
}
}
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let (sink, _collected) = EventSink::collecting("compact-test");
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let seen: Arc<Mutex<Vec<(usize, bool)>>> = Arc::new(Mutex::new(Vec::new()));
let gen = RecordingGen {
seen: seen.clone(),
turn_no: AtomicUsize::new(0),
};
let cfg = NativeLoopConfig {
model: Some("scripted".into()),
max_iterations: 1,
max_turns_per_iteration: 12,
max_tokens_per_turn: 4096,
};
let contract = OutcomeContract {
description: "never satisfied".into(),
checks: vec![ContractCheck {
name: "never".into(),
command: crate::coder::test_cmds::FAIL.to_string(),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 10,
}],
};
let _ = run_native_loop(
&gen,
&executor,
"grow the thread",
&contract,
&sink,
&cancel,
&cfg,
&RepairMemory::disabled(),
None,
)
.await;
let seen = seen.lock().unwrap();
assert_eq!(seen.len(), 12, "all 12 turns generated");
// The System prompt (outcome contract) is pinned at the head EVERY turn —
// compaction never drops it.
assert!(
seen.iter().all(|(_, sys)| *sys),
"System prompt must stay pinned every turn"
);
// Bounded: absent compaction the 12th turn would see ~2 + 2*11 = 24
// messages. Compaction caps it near the pinned head + recent tail.
let max_len = seen.iter().map(|(n, _)| *n).max().unwrap();
assert!(
max_len < 14,
"persistent history not bounded — max messages/turn = {max_len}"
);
}
#[tokio::test]
async fn native_loop_routes_high_stakes() {
// The coder loop edits and runs code in a real worktree, so EVERY
// inference it issues must carry the high_stakes hint (quality-first) —
// a wrong edit lands in a real repo. Capture every turn's intent (not
// just the first) so the invariant survives a future refactor that might
// hoist intent-setting out of the per-turn loop into a branch.
use std::sync::Mutex;
struct CapturingGen {
intents: Arc<Mutex<Vec<Option<car_inference::IntentHint>>>>,
cursor: AtomicUsize,
}
#[async_trait]
impl TurnGenerator for CapturingGen {
async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String> {
self.intents.lock().unwrap().push(req.intent.clone());
// Turn 0 issues a tool call so the loop runs a SECOND turn; turn
// 1 declares done so it then exits. Two captured intents prove
// the hint rides every turn, not just the first.
let i = self.cursor.fetch_add(1, Ordering::SeqCst);
if i == 0 {
Ok(turn(
"",
serde_json::json!([{
"id": "c1", "name": "write_file",
"arguments": {"path": "f.txt", "content": "x"}
}]),
))
} else {
Ok(turn("done", serde_json::json!([])))
}
}
}
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let sink = EventSink::test_sink();
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let captured = Arc::new(Mutex::new(Vec::new()));
let gen = CapturingGen {
intents: captured.clone(),
cursor: AtomicUsize::new(0),
};
let contract = OutcomeContract {
description: "noop".into(),
checks: vec![],
};
let _ = run_native_loop(
&gen,
&executor,
"make a change",
&contract,
&sink,
&cancel,
&NativeLoopConfig::default(),
&RepairMemory::disabled(),
None,
)
.await;
let intents = captured.lock().unwrap();
assert!(
intents.len() >= 2,
"expected the loop to issue multiple inferences, got {}",
intents.len()
);
for (n, intent) in intents.iter().enumerate() {
let intent = intent
.as_ref()
.unwrap_or_else(|| panic!("turn {n} issued an inference with no IntentHint"));
assert!(intent.high_stakes, "turn {n} must route high_stakes");
assert_eq!(
intent.task,
Some(car_inference::TaskHint::Code),
"turn {n} must keep the Code task hint"
);
}
}
#[tokio::test]
async fn scripted_loop_repairs_after_red_checks() {
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let sink = EventSink::test_sink();
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
// Iter 1: writes the WRONG content, says done → check fails.
// Iter 2: fixes it → check passes.
let script = Script {
turns: vec![
turn(
"",
serde_json::json!([{
"id": "c1", "name": "write_file",
"arguments": {"path": "x.txt", "content": "wrong"}
}]),
),
turn("done", serde_json::json!([])),
turn(
"",
serde_json::json!([{
"id": "c2", "name": "write_file",
"arguments": {"path": "x.txt", "content": "right"}
}]),
),
turn("fixed", serde_json::json!([])),
],
cursor: AtomicUsize::new(0),
};
let contract = OutcomeContract {
description: "x.txt says right".into(),
checks: vec![ContractCheck {
name: "content".into(),
command: crate::coder::test_cmds::contains_or_report("right", "x.txt"),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 10,
}],
};
let outcome = run_native_loop(
&script,
&executor,
"write right into x.txt",
&contract,
&sink,
&cancel,
&NativeLoopConfig::default(),
&RepairMemory::disabled(),
None,
)
.await;
assert!(outcome.passed);
assert_eq!(outcome.iterations, 2, "one repair round expected");
}
/// F2 (audit 2026-07-06): the coder must PERSIST its conversation across
/// repair iterations — the files it read, the edits it made, the dead-ends
/// it ruled out — appending the failing-check feedback as a new turn rather
/// than resetting to `[System, User]` each round. Prove it: iteration 2's
/// first inference must carry iteration 1's tool call.
#[tokio::test]
async fn f2_iteration_two_carries_iteration_one_conversation() {
use std::sync::Mutex as StdMutex;
struct MsgCapture {
seen: Arc<StdMutex<Vec<String>>>,
cursor: AtomicUsize,
}
#[async_trait]
impl TurnGenerator for MsgCapture {
async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String> {
self.seen
.lock()
.unwrap()
.push(serde_json::to_string(&req.messages).unwrap_or_default());
let i = self.cursor.fetch_add(1, Ordering::SeqCst);
match i {
0 => Ok(turn(
"",
serde_json::json!([{
"id": "iter1call", "name": "write_file",
"arguments": {"path": "x.txt", "content": "ITER1_WRONG"}
}]),
)),
1 => Ok(turn("done", serde_json::json!([]))),
2 => Ok(turn(
"",
serde_json::json!([{
"id": "iter2call", "name": "write_file",
"arguments": {"path": "x.txt", "content": "ITER2_right"}
}]),
)),
_ => Ok(turn("fixed", serde_json::json!([]))),
}
}
}
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let sink = EventSink::test_sink();
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let seen = Arc::new(StdMutex::new(Vec::new()));
let gen = MsgCapture {
seen: seen.clone(),
cursor: AtomicUsize::new(0),
};
let contract = OutcomeContract {
description: "x.txt says ITER2_right".into(),
checks: vec![ContractCheck {
name: "content".into(),
command: crate::coder::test_cmds::contains("ITER2_right", "x.txt"),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 10,
}],
};
let outcome = run_native_loop(
&gen,
&executor,
"write ITER2_right into x.txt",
&contract,
&sink,
&cancel,
&NativeLoopConfig::default(),
&RepairMemory::disabled(),
None,
)
.await;
assert!(outcome.passed);
assert_eq!(outcome.iterations, 2, "expected a repair round");
let seen = seen.lock().unwrap();
assert!(
seen.len() >= 4,
"expected >=4 inferences, got {}",
seen.len()
);
// Iteration 2's opening inference must carry iteration 1's tool call —
// the conversation is persisted, not reset.
assert!(
seen[2].contains("ITER1_WRONG") || seen[2].contains("iter1call"),
"F2: iteration 2 lost iteration 1's conversation:\n{}",
seen[2]
);
}
/// F3 (audit 2026-07-06): a turn that hit the max_tokens ceiling
/// (stop_reason=length) is CUT OFF, not a completion. The loop must NOT
/// treat an empty-tool-call truncated turn as "done" — it must recognize
/// the truncation and continue so the model can finish.
#[tokio::test]
async fn f3_truncated_turn_is_not_treated_as_done() {
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let sink = EventSink::test_sink();
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let script = Script {
turns: vec![
// Turn 0: truncated mid-thought — no tool calls, stop_reason=length.
turn_with_stop(
"partial output that got cut o",
serde_json::json!([]),
Some("length"),
),
// Turn 1: a clean, natural completion.
turn_with_stop("done for real", serde_json::json!([]), Some("stop")),
],
cursor: AtomicUsize::new(0),
};
let contract = OutcomeContract {
description: "noop".into(),
checks: vec![],
};
let _ = run_native_loop(
&script,
&executor,
"do the thing",
&contract,
&sink,
&cancel,
&NativeLoopConfig::default(),
&RepairMemory::disabled(),
None,
)
.await;
// The truncated first turn must not end the iteration: the loop should
// continue and consume the SECOND scripted turn (cursor advances to 2).
assert_eq!(
script.cursor.load(Ordering::SeqCst),
2,
"truncated turn was mistaken for completion — loop stopped early instead of continuing"
);
}
/// End-to-end learning: a repair (red → green) records a durable skill
/// keyed on the failure signature, and a *fresh* session that hits the same
/// signature recalls that approach into its repair prompt.
#[tokio::test]
async fn repair_round_learns_and_recalls_across_sessions() {
use crate::coder::skill_memory::FailureSignature;
use car_memgine::MemgineEngine;
use tokio::sync::Mutex as AsyncMutex;
// A shared memgine survives both sessions (the "gets better" store).
let memory = RepairMemory::new(Some(Arc::new(AsyncMutex::new(MemgineEngine::new(None)))));
// A contract whose check fails LOUDLY with a recognizable error class
// so the signature is stable across sessions.
let contract = OutcomeContract {
description: "x.txt says right".into(),
checks: vec![ContractCheck {
name: "content".into(),
command: crate::coder::test_cmds::contains_or_report("right", "x.txt"),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 10,
}],
};
let sig = FailureSignature {
check: "content".into(),
error_class: "test_failure".into(),
};
// --- Session 1: red then green. The green-after-red ingests the skill.
let dir1 = tempfile::tempdir().unwrap();
let exec1 = WorktreeExecutor::new(dir1.path());
let sink = EventSink::test_sink();
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let script1 = Script {
turns: vec![
turn(
"",
serde_json::json!([{
"id": "c1", "name": "write_file",
"arguments": {"path": "x.txt", "content": "wrong"}
}]),
),
turn("nothing useful yet", serde_json::json!([])),
turn(
"",
serde_json::json!([{
"id": "c2", "name": "write_file",
"arguments": {"path": "x.txt", "content": "right"}
}]),
),
turn(
"wrote 'right' into x.txt to satisfy the grep",
serde_json::json!([]),
),
],
cursor: AtomicUsize::new(0),
};
let outcome1 = run_native_loop(
&script1,
&exec1,
"write right into x.txt",
&contract,
&sink,
&cancel,
&NativeLoopConfig::default(),
&memory,
None,
)
.await;
assert!(outcome1.passed);
// The winning approach is now durably recallable for this signature.
let recalled = memory
.recall(&sig)
.await
.expect("session 1 should have learned");
assert!(recalled.contains("right"), "approach captured: {recalled}");
// --- Session 2: the SAME signature recurs. The loop must inject the
// recalled hint into the repair prompt on the second iteration.
let dir2 = tempfile::tempdir().unwrap();
let exec2 = WorktreeExecutor::new(dir2.path());
let (sink2, collected) = EventSink::collecting("coder-learn");
let seen_hint = Arc::new(std::sync::atomic::AtomicBool::new(false));
// A generator that asserts on the prompt it receives: once a recall
// hint shows up in the user message, it writes the fix.
struct HintWatcher {
seen: Arc<std::sync::atomic::AtomicBool>,
cursor: AtomicUsize,
}
#[async_trait]
impl TurnGenerator for HintWatcher {
async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String> {
let i = self.cursor.fetch_add(1, Ordering::SeqCst);
let saw_hint = req
.messages
.as_ref()
.map(|ms| {
ms.iter().any(
|m| matches!(m, Message::User { content } if content.contains("HINT")),
)
})
.unwrap_or(false);
if saw_hint {
self.seen.store(true, Ordering::SeqCst);
}
Ok(match i {
// Iter 1: do nothing → contract red → signature recorded.
0 => turn("did nothing", serde_json::json!([])),
// Iter 2 (hint present): write the fix.
1 => turn(
"",
serde_json::json!([{
"id": "c1", "name": "write_file",
"arguments": {"path": "x.txt", "content": "right"}
}]),
),
_ => turn("applied the recalled fix", serde_json::json!([])),
})
}
}
let script2 = HintWatcher {
seen: seen_hint.clone(),
cursor: AtomicUsize::new(0),
};
let outcome2 = run_native_loop(
&script2,
&exec2,
"write right into x.txt",
&contract,
&sink2,
&cancel,
&NativeLoopConfig::default(),
&memory,
None,
)
.await;
assert!(outcome2.passed, "session 2 should pass: {outcome2:?}");
assert!(
seen_hint.load(Ordering::SeqCst),
"the recalled hint must have been injected into the repair prompt"
);
drop(collected);
}
/// The `ask_user` tool routes to the [`AskUser`] handler (not the worktree
/// executor), emits `UserInputRequested`, and the handler's answer is fed
/// back to the model as the tool result — which the model then uses.
#[tokio::test]
async fn ask_user_tool_routes_to_handler_and_answer_reaches_model() {
use std::sync::Mutex as StdMutex;
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let (sink, collected) = EventSink::collecting("coder-ask");
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
// A canned asker that records the prompt it saw and returns a fixed
// answer (stands in for the gate + coder.respond round-trip).
struct CannedAsker {
seen_prompt: Arc<StdMutex<Option<String>>>,
answer: String,
}
#[async_trait]
impl AskUser for CannedAsker {
async fn ask(&self, prompt: &str) -> Result<String, String> {
*self.seen_prompt.lock().unwrap() = Some(prompt.to_string());
Ok(self.answer.clone())
}
}
let seen_prompt = Arc::new(StdMutex::new(None));
let asker = CannedAsker {
seen_prompt: seen_prompt.clone(),
answer: "use port 8080".to_string(),
};
// The script: ask a question, then (turn 2) write the answer it got
// back into a file, then declare done. A generator that echoes the
// ask_user tool result into the write proves the answer reached it.
struct AskThenWrite {
cursor: AtomicUsize,
}
#[async_trait]
impl TurnGenerator for AskThenWrite {
async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String> {
let i = self.cursor.fetch_add(1, Ordering::SeqCst);
match i {
0 => Ok(turn(
"",
serde_json::json!([{
"id": "a1", "name": "ask_user",
"arguments": {"prompt": "which port?"}
}]),
)),
1 => {
// Pull the answer out of the ToolResult the loop appended.
let answer = req
.messages
.as_ref()
.and_then(|ms| {
ms.iter().rev().find_map(|m| match m {
Message::ToolResult { content, .. } => Some(content.clone()),
_ => None,
})
})
.unwrap_or_default();
Ok(turn(
"",
serde_json::json!([{
"id": "w1", "name": "write_file",
"arguments": {"path": "answer.txt", "content": answer}
}]),
))
}
_ => Ok(turn("done", serde_json::json!([]))),
}
}
}
let contract = OutcomeContract {
description: "answer.txt records the chosen port".into(),
checks: vec![ContractCheck {
name: "has_port".into(),
command: crate::coder::test_cmds::contains("8080", "answer.txt"),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 10,
}],
};
let outcome = run_native_loop(
&AskThenWrite {
cursor: AtomicUsize::new(0),
},
&executor,
"pick a port and record it",
&contract,
&sink,
&cancel,
&NativeLoopConfig::default(),
&RepairMemory::disabled(),
Some(&asker),
)
.await;
assert!(outcome.passed, "outcome: {outcome:?}");
// The handler saw the model's question.
assert_eq!(seen_prompt.lock().unwrap().as_deref(), Some("which port?"));
// The answer reached the model and was written through.
assert_eq!(
std::fs::read_to_string(dir.path().join("answer.txt")).unwrap(),
"use port 8080"
);
// The ask_user call surfaced in the event stream as a tool call (the
// semantic UserInputRequested event is the GateAsker's job, covered by
// the rpc round-trip test).
let events = collected.lock().unwrap();
assert!(events.iter().any(|e| matches!(
&e.kind,
CoderEventKind::ToolCall { tool, .. } if tool == ASK_USER_TOOL
)));
}
/// Without an asker the `ask_user` tool is not offered, and if a model calls
/// it anyway the loop returns a recoverable tool error rather than wedging.
#[tokio::test]
async fn ask_user_without_handler_is_a_recoverable_error() {
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let (sink, _collected) = EventSink::collecting("coder-noask");
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
// ask_user is absent from the offered tools when ask is None.
struct ToolPeek {
offered: Arc<std::sync::atomic::AtomicBool>,
}
#[async_trait]
impl TurnGenerator for ToolPeek {
async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String> {
let has_ask = req
.tools
.as_ref()
.map(|ts| ts.iter().any(|t| t["name"] == ASK_USER_TOOL))
.unwrap_or(false);
self.offered.store(has_ask, Ordering::SeqCst);
Ok(turn("done", serde_json::json!([])))
}
}
let offered_flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let contract = OutcomeContract {
description: "noop".into(),
checks: vec![ContractCheck {
name: "ok".into(),
command: crate::coder::test_cmds::PASS.to_string(),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 10,
}],
};
let _ = run_native_loop(
&ToolPeek {
offered: offered_flag.clone(),
},
&executor,
"x",
&contract,
&sink,
&cancel,
&NativeLoopConfig::default(),
&RepairMemory::disabled(),
None,
)
.await;
assert!(
!offered_flag.load(Ordering::SeqCst),
"ask_user must not be offered when no handler is wired"
);
}
#[tokio::test]
async fn cancellation_stops_the_loop() {
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let sink = EventSink::test_sink();
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(true));
let script = Script {
turns: vec![],
cursor: AtomicUsize::new(0),
};
let contract = OutcomeContract {
description: "d".into(),
checks: vec![ContractCheck {
name: "never".into(),
command: crate::coder::test_cmds::PASS.to_string(),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 10,
}],
};
let outcome = run_native_loop(
&script,
&executor,
"x",
&contract,
&sink,
&cancel,
&NativeLoopConfig::default(),
&RepairMemory::disabled(),
None,
)
.await;
assert_eq!(outcome.error.as_deref(), Some("cancelled"));
assert_eq!(outcome.iterations, 0);
}
#[test]
fn failure_feedback_lists_only_failures() {
let results = vec![
CheckResult {
name: "good".into(),
passed: true,
exit_code: Some(0),
output_tail: "ok".into(),
duration_ms: 1,
},
CheckResult {
name: "bad".into(),
passed: false,
exit_code: Some(1),
output_tail: "assertion failed".into(),
duration_ms: 1,
},
];
let fb = failure_feedback(&results, 0);
assert!(fb.contains("FAILED bad"));
assert!(fb.contains("assertion failed"));
assert!(!fb.contains("FAILED good"));
// A fresh failure gets the read-the-error direction, not the escalation.
assert!(fb.contains("name the single cause"));
assert!(!fb.contains("failed 2 times in a row"));
}
#[test]
fn failure_feedback_escalates_on_a_recurring_failure() {
let results = vec![CheckResult {
name: "run_tests".into(),
passed: false,
exit_code: Some(1),
output_tail: "AttributeError: no attribute '_remove_slot_root'".into(),
duration_ms: 1,
}];
// Same check failing a 2nd time (streak=1) → escalate: stop repeating the
// approach, implement the named missing symbol.
let fb = failure_feedback(&results, 1);
assert!(fb.contains("failed 2 times in a row"));
assert!(fb.contains("do NOT re-apply a variation"));
assert!(fb.contains("IMPLEMENT it"));
}
#[test]
fn system_prompt_carries_the_contract() {
let contract = OutcomeContract {
description: "make the tests pass".into(),
checks: vec![super::super::contract::ContractCheck {
name: "tests".into(),
command: "cargo test -p demo".into(),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 300,
}],
};
let p = system_prompt(&contract, "Top-level entries: Cargo.toml, src");
assert!(p.contains("cargo test -p demo"));
assert!(p.contains("STOP calling tools"));
// The coder must self-verify with the contract's exact command, not a
// broad guess (a broad run in a large repo trips on unrelated breakage).
assert!(p.contains("EXACT command(s) from the OUTCOME CONTRACT"));
}
#[test]
fn coder_prompt_contains_discipline_and_keeps_stop_contract() {
let contract = OutcomeContract {
description: "make the tests pass".into(),
checks: vec![ContractCheck {
name: "tests".into(),
command: "cargo test -p demo".into(),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 300,
}],
};
let env = "Top-level entries: Cargo.toml, src\nBuild systems detected: Rust (cargo)";
let p = system_prompt(&contract, env);
// Real coding discipline is present.
assert!(p.contains("Inspect before you edit"), "inspect-first");
assert!(
p.contains("grep_files") && p.contains("find_files"),
"search-before-read discipline"
);
assert!(p.contains("prefer edit_file"), "surgical-edit discipline");
assert!(
p.contains("Never fabricate file contents"),
"anti-fabrication (files)"
);
assert!(
p.contains("Never claim a check passed"),
"anti-fabrication (results)"
);
assert!(
p.contains("read the actual error output before retrying"),
"read-the-error discipline"
);
// Dogfooding fix #1: a blocked self-verify must not be reported as failure.
assert!(
p.contains("is NOT a task failure") && p.contains("blocked"),
"blocked-verification-is-not-failure guidance"
);
// Dogfooding fix #3 (evidence-backed A/B, 55%->100%): trace each check +
// watch order/exact-value pitfalls.
assert!(
p.contains("Trace the checks before you declare done")
&& p.contains("preserve first-seen ORDER"),
"check-tracing + pitfall guidance"
);
// Dogfooding fix (A/B 809s vs 58s root-cause): the coder fixed the bug in
// ~6 turns then burned ~30 fighting a python3.14 self-verify env mismatch —
// ran plain `python -m pytest` (wrong interpreter), then wrote
// sitecustomize.py/UserDict.py shims + pip install to "repair" it. Two hard
// rules now: verify with the contract's EXACT command, and NEVER repair the
// environment.
assert!(
p.contains("copy the command string character-for-character"),
"exact-command self-verify (no broad substitute)"
);
assert!(
p.contains("NEVER repair, reconfigure, or work around the environment")
&& p.contains("STRICTLY FORBIDDEN")
&& p.contains("sitecustomize.py"),
"no-environment-repair hard rule"
);
// The runtime-verifies framing is REFRAMED (verify yourself first), not
// a promise the runtime does it for you.
assert!(p.contains("do not rely on it: verify the checks yourself first"));
// Load-bearing behavior contracts are preserved verbatim / accurately.
assert!(
p.contains("reply with a brief plain-text summary and STOP calling tools"),
"the STOP-calling-tools loop-termination contract must survive verbatim"
);
assert!(p.contains("Do not git commit"), "policy: no git commit");
assert!(
p.contains("denies git push, sudo"),
"policy: no push/sudo/destructive"
);
// The ENVIRONMENT section (F7/L1) carries the repo summary.
assert!(p.contains("ENVIRONMENT:"));
assert!(p.contains("Rust (cargo)"));
// And the outcome contract is still rendered.
assert!(p.contains("cargo test -p demo"));
}
#[test]
fn preview_truncates_on_char_boundary() {
assert_eq!(preview("short", 10), "short");
let long = "é".repeat(300);
let p = preview(&long, 5);
assert!(p.ends_with('…') && p.chars().count() <= 4);
}
/// A generator that captures the FIRST user message of the request it
/// receives, then declares done — for asserting what the model sees on the
/// opening turn.
struct FirstUserCapture {
captured: Arc<std::sync::Mutex<String>>,
}
#[async_trait]
impl TurnGenerator for FirstUserCapture {
async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String> {
let first_user = req
.messages
.as_ref()
.and_then(|ms| {
ms.iter().find_map(|m| match m {
Message::User { content } => Some(content.clone()),
_ => None,
})
})
.unwrap_or_default();
*self.captured.lock().unwrap() = first_user;
Ok(turn("done", serde_json::json!([])))
}
}
fn trivial_contract() -> OutcomeContract {
OutcomeContract {
description: "trivial".into(),
checks: vec![ContractCheck {
name: "ok".into(),
command: crate::coder::test_cmds::PASS.to_string(),
expect_exit_zero: true,
output_contains: None,
timeout_secs: 10,
}],
}
}
#[tokio::test]
async fn coder_first_message_carries_recall_when_facts_exist() {
use crate::coder::skill_memory::FailureSignature;
use car_memgine::MemgineEngine;
use tokio::sync::Mutex as AsyncMutex;
// Seed a shared engine with a prior-session repair lead overlapping the
// intent keywords ("tests").
let memory = RepairMemory::new(Some(Arc::new(AsyncMutex::new(MemgineEngine::new(None)))));
let sig = FailureSignature {
check: "tests".into(),
error_class: "test_failure".into(),
};
memory
.record_success(&sig, "add the missing import and re-run cargo test")
.await;
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let sink = EventSink::test_sink();
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let captured = Arc::new(std::sync::Mutex::new(String::new()));
let outcome = run_native_loop(
&FirstUserCapture {
captured: captured.clone(),
},
&executor,
"the tests are failing, please fix them",
&trivial_contract(),
&sink,
&cancel,
&NativeLoopConfig::default(),
&memory,
None,
)
.await;
assert!(outcome.passed, "outcome: {outcome:?}");
let first_user = captured.lock().unwrap().clone();
assert!(
first_user.contains("Recall from prior sessions"),
"the labelled session-start recall must be in the first user turn: {first_user}"
);
assert!(
first_user.contains("missing import"),
"the recalled approach content rides along: {first_user}"
);
}
#[tokio::test]
async fn coder_first_message_recall_absent_when_empty() {
use car_memgine::MemgineEngine;
use tokio::sync::Mutex as AsyncMutex;
// A live engine with NOTHING learned → recall_for_task returns None →
// no recall section is injected (no empty boilerplate).
let memory = RepairMemory::new(Some(Arc::new(AsyncMutex::new(MemgineEngine::new(None)))));
let dir = tempfile::tempdir().unwrap();
let executor = WorktreeExecutor::new(dir.path());
let sink = EventSink::test_sink();
let cancel: CancelFlag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let captured = Arc::new(std::sync::Mutex::new(String::new()));
let outcome = run_native_loop(
&FirstUserCapture {
captured: captured.clone(),
},
&executor,
"the tests are failing, please fix them",
&trivial_contract(),
&sink,
&cancel,
&NativeLoopConfig::default(),
&memory,
None,
)
.await;
assert!(outcome.passed, "outcome: {outcome:?}");
let first_user = captured.lock().unwrap().clone();
assert!(
!first_user.contains("Recall from prior sessions"),
"no recall section when the engine has nothing relevant: {first_user}"
);
}
}