argonauts-app 0.1.0

Argonauts Code's app controller and run host: the conversation, routing, choosing Captain or crew, and the run host each run has.
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
//! Direct Captain through the real controller loop, with fake CLIs: the Captain workflow and
//! `/captain` send your words to the main session in your checkout, it ends with its own answer, it
//! asks like its CLI in supervised mode and not in auto, it falls back when it runs out, `/rewind`
//! puts files back, and checked Captain still runs as a run.

use std::path::Path;
use std::time::Duration;

use argonauts_core::app::{
    AnswerTarget, AppEvent, ChoiceKind, ConversationEvent, TurnReply, UiCommand,
};
use argonauts_core::asking::{Ask, AskLine, AskReply};
use argonauts_core::event::AgentEvent;
use argonauts_core::events::approval::AnswerAction;
use argonauts_core::events::run::{InstructionOutcome, RunMode};
use argonauts_core::events::session::{CallCount, EndReason, InputPartKind, Watchdog};
use argonauts_core::input::SlashCommand;
use argonauts_core::session_runner::{Access, RunnerEvent, SessionControl, SessionSpec};
use argonauts_core::settings::approvals::ApprovalMode;
use argonauts_core::{Asks, sha256_hex};
use argonauts_testkit::{FakeRunner, FakeSession};
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;

use crate::controller::test_support::{CliOptions, TestDriver, WAIT};

use super::direct_outside_tests::written_by;

const TASK: &str = "The tests in tests/test_money.py fail. Fix invoice/money.py so every test \
                    passes, without changing the tests.";
const ANSWER: &str = "Fixed both functions in invoice/money.py. All 6 tests pass.";

/// The Captain workflow, with whatever else `config` adds to your global settings.
fn captain_workflow_options(config: &'static str) -> CliOptions {
    CliOptions {
        prepare: Some(Box::new(move |repo: &argonauts_testkit::TempRepo| {
            repo.write("invoice/money.py", "sign = 1\n").unwrap();
            repo.commit_all("money").unwrap();
            std::fs::write(
                repo.global_config(),
                format!("{config}\n[captain_or_crew]\nforce = \"captain\"\n"),
            )
            .unwrap();
        })),
        ..CliOptions::default()
    }
}

const SUPERVISED: &str = "[approvals.understand]\nmode = \"supervised\"\n";

/// A session that edits `invoice/money.py` in the folder it was given, runs the tests, and
/// answers, slowly enough for a test to ask a question meanwhile.
fn fixing(delay: Duration) -> impl Fn(&SessionSpec) -> FakeSession + Send + Sync + 'static {
    move |spec: &SessionSpec| {
        std::fs::write(spec.workdir.join("invoice/money.py"), "negative = True\n").unwrap();
        FakeSession::completed(ANSWER)
            .with_event(tool("t1", "Edit", json!({"file_path": "invoice/money.py"})))
            .with_event(RunnerEvent::Agent(AgentEvent::ToolFinished {
                id: "t1".into(),
                ok: true,
                output: Some("Added 1 line, removed 1 line".into()),
                parent: None,
            }))
            .with_delay(delay)
    }
}

fn tool(id: &str, name: &str, input: Value) -> RunnerEvent {
    RunnerEvent::Agent(AgentEvent::ToolStarted {
        id: id.into(),
        name: name.into(),
        input,
        parent: None,
    })
}

/// What a CLI's adapter reports once a tool call's write to `path` is done.
fn changed(path: &str) -> RunnerEvent {
    RunnerEvent::Agent(AgentEvent::FileChanged {
        path: path.into(),
        kind: "update".into(),
    })
}

fn conversation(event: &AppEvent) -> Option<&ConversationEvent> {
    match event {
        AppEvent::Conversation { event } => Some(event),
        _ => None,
    }
}

fn turn_ended(event: &AppEvent) -> bool {
    matches!(
        conversation(event),
        Some(ConversationEvent::TurnFinished { .. } | ConversationEvent::TurnFailed { .. })
    )
}

fn choose(id: argonauts_core::names::ChoiceId, value: &str) -> UiCommand {
    UiCommand::Answer {
        to: AnswerTarget::Choice { id },
        action: AnswerAction::Choose {
            value: value.to_owned(),
        },
        text: None,
        evidence_sha256: None,
        tasks: Vec::new(),
        remember: false,
    }
}

fn read(root: &Path, path: &str) -> String {
    std::fs::read_to_string(root.join(path)).unwrap()
}

/// Asks the turn's listener as the session's MCP server does, and waits for the answer.
async fn ask(spec: &SessionSpec, ask: Ask) -> AskReply {
    let asking = spec.asking.clone().expect("the turn listens for questions");
    let mut stream = TcpStream::connect(&asking.endpoint).await.unwrap();
    let line = AskLine {
        token: asking.token,
        ask,
    };
    let text = format!("{}\n", serde_json::to_string(&line).unwrap());
    stream.write_all(text.as_bytes()).await.unwrap();
    let mut answer = String::new();
    BufReader::new(stream).read_line(&mut answer).await.unwrap();
    serde_json::from_str(answer.trim()).unwrap()
}

async fn first_spec(driver: &TestDriver) -> SessionSpec {
    let deadline = tokio::time::Instant::now() + WAIT;
    loop {
        if let Some(spec) = driver.agent.specs().into_iter().next() {
            return spec;
        }
        assert!(tokio::time::Instant::now() < deadline, "no session started");
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
}

/// A direct turn in the Captain workflow: the message goes to Claude Code in your checkout as
/// you typed it, the file changes there, and the turn ends with the agent's own answer. No run,
/// worktree, task, report, recap, or learned workflow.
#[tokio::test]
async fn a_direct_turn_edits_your_checkout_and_ends_with_the_agents_answer() {
    let mut driver = TestDriver::start_with(captain_workflow_options("")).await;
    let root = driver.repo.root().to_owned();
    driver.agent.respond(fixing(Duration::ZERO));
    let worker = driver.agent.clone();
    let text = format!("{TASK} See @README.md");
    driver.submit(&text).await;
    let ended = driver.until(turn_ended).await;
    let money = read(&root, "invoice/money.py");
    let events = driver.exit().await;

    assert!(matches!(
        conversation(&ended),
        Some(ConversationEvent::TurnFinished { reply: TurnReply::Answer { markdown }, .. }) if markdown == ANSWER
    ));
    let spec = worker.specs().remove(0);
    assert_eq!(spec.access, Access::Direct);
    assert_eq!(spec.workdir, root);
    assert!(spec.json_schema.is_none());
    assert_eq!(spec.goal_sha256, Some(sha256_hex(text.as_bytes())));
    // Your words as typed, then the file you mentioned, and nothing of Argonauts Code's own.
    let kinds: Vec<_> = spec.prompt.iter().map(|part| part.kind).collect();
    assert_eq!(kinds, [InputPartKind::Message, InputPartKind::File]);
    assert_eq!(spec.prompt[0].text, text);
    assert_eq!(money, "negative = True\n");

    let started = events.iter().find_map(|event| match conversation(event) {
        Some(ConversationEvent::TurnStarted { read_only, .. }) => Some(*read_only),
        _ => None,
    });
    assert_eq!(started, Some(false), "a direct turn says it may write");
    assert!(cli_starts_nothing(&events));
    assert!(
        !events
            .iter()
            .any(|event| matches!(event, AppEvent::Recap { .. })),
        "no recap repeats the answer"
    );
}

fn cli_starts_nothing(events: &[AppEvent]) -> bool {
    !events.iter().any(|event| {
        matches!(event, AppEvent::Run { .. })
            || matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::StartWork)
    })
}

/// `/captain` is direct too, without the workflow, and checked Captain still starts a run.
#[tokio::test]
async fn slash_captain_is_direct_and_checked_captain_is_a_run() {
    let captain = |config: &'static str| CliOptions {
        prepare: Some(Box::new(move |repo: &argonauts_testkit::TempRepo| {
            std::fs::write(repo.global_config(), config).unwrap();
        })),
        ..CliOptions::default()
    };
    let slash = UiCommand::Slash {
        command: SlashCommand::Captain {
            task: "fix the typo in the README".to_owned(),
        },
    };

    let mut driver = TestDriver::start_with(captain("")).await;
    driver.agent.push(FakeSession::completed("Fixed the typo."));
    driver.send(slash.clone()).await;
    driver.until(turn_ended).await;
    let conductor = driver.conductor.clone();
    let specs = driver.agent.specs();
    driver.exit().await;
    assert_eq!(specs[0].access, Access::Direct);
    assert!(conductor.starts().is_empty());

    for checked in [
        "[captain]\nkind = \"checked\"\n",
        "[captain]\nreview = true\n",
    ] {
        let driver = TestDriver::start_with(captain(checked)).await;
        driver.send(slash.clone()).await;
        let conductor = driver.conductor.clone();
        let deadline = tokio::time::Instant::now() + WAIT;
        while conductor.starts().is_empty() {
            assert!(tokio::time::Instant::now() < deadline, "{checked}");
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        let start = conductor.starts().remove(0);
        assert_eq!((start.mode, start.forced), (RunMode::Captain, true));
        assert!(driver.agent.specs().is_empty());
        driver.exit().await;
    }
}

/// The turn's controls that say a question from its CLI waits on you, or was answered.
fn asking_controls(driver: &TestDriver) -> Vec<SessionControl> {
    driver
        .agent
        .controls()
        .into_iter()
        .map(|(_, control)| control)
        .filter(|control| matches!(control, SessionControl::Asking | SessionControl::Answered))
        .collect()
}

/// A permission question waits on you however long you take, and the CLI sends nothing
/// meanwhile, so the turn's session is told it waits: its inactivity watchdog counts none of
/// that time, and the clock starts again once you answer.
#[tokio::test]
async fn a_question_waiting_on_you_holds_the_turns_inactivity_clock() {
    let mut driver = TestDriver::start_with(captain_workflow_options(SUPERVISED)).await;
    driver
        .agent
        .push(FakeSession::completed(ANSWER).with_delay(Duration::from_secs(2)));
    driver.submit(TASK).await;
    let spec = first_spec(&driver).await;
    let command = Ask::Permission {
        tool_name: "Bash".into(),
        input: json!({"command": "python -m pytest -q"}),
        tool_use_id: None,
    };
    let answered = tokio::spawn({
        let spec = spec.clone();
        async move { ask(&spec, command).await }
    });
    let question = driver
        .until(|event| matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::Permission))
        .await;
    let AppEvent::Choice { choice } = question else {
        unreachable!()
    };
    driver.send(choose(choice.id, "yes")).await;
    assert!(answered.await.unwrap().text.contains("\"allow\""));
    driver.until(turn_ended).await;
    // The fake session reads its controls as it ends, in the order they were sent.
    assert_eq!(
        asking_controls(&driver),
        [SessionControl::Asking, SessionControl::Answered]
    );
    driver.exit().await;
}

/// Supervised mode asks what Claude Code asks: an edit becomes a question, Yes lets it through,
/// "allow edits" answers later edits itself for this conversation, "don't ask again" saves the
/// command's pattern at "This project, just me", and No stops the turn.
#[tokio::test]
async fn supervised_asks_like_the_cli_and_remembers_what_you_allow() {
    let mut driver = TestDriver::start_with(captain_workflow_options(SUPERVISED)).await;
    driver
        .agent
        .push(FakeSession::completed(ANSWER).with_delay(Duration::from_secs(2)));
    driver.submit(TASK).await;
    let spec = first_spec(&driver).await;
    let asking = spec.asking.clone().expect("supervised asks");
    assert_eq!(asking.asks, Asks::LikeCli);

    let edit = Ask::Permission {
        tool_name: "Edit".into(),
        input: json!({"file_path": "invoice/money.py", "old_string": "sign = 1", "new_string": "x"}),
        tool_use_id: Some("t1".into()),
    };
    let answered = tokio::spawn({
        let spec = spec.clone();
        let edit = edit.clone();
        async move { ask(&spec, edit).await }
    });
    let question = driver
        .until(|event| matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::Permission))
        .await;
    let AppEvent::Choice { choice } = question else {
        unreachable!()
    };
    assert_eq!(choice.title, "Make this edit to invoice/money.py?");
    assert_eq!(choice.body, ["- sign = 1", "+ x"]);
    driver.send(choose(choice.id, "always")).await;
    let reply = answered.await.unwrap();
    assert!(reply.text.contains("\"allow\""), "{reply:?}");

    // Edits are allowed for the rest of the conversation: no question for this one.
    let again = ask(&spec, edit).await;
    assert!(again.text.contains("\"allow\""));

    let command = Ask::Permission {
        tool_name: "Bash".into(),
        input: json!({"command": "python -m pytest -q"}),
        tool_use_id: None,
    };
    let answered = tokio::spawn({
        let spec = spec.clone();
        async move { ask(&spec, command).await }
    });
    let question = driver
        .until(|event| matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::Permission))
        .await;
    let AppEvent::Choice { choice } = question else {
        unreachable!()
    };
    assert_eq!(choice.title, "Run this command?");
    assert!(
        choice.options[1].label.contains("python -m pytest"),
        "{:?}",
        choice.options
    );
    driver.send(choose(choice.id, "always")).await;
    assert!(answered.await.unwrap().text.contains("\"allow\""));
    let local = driver.repo.root().join(".argonauts/config.local.toml");
    let saved = std::fs::read_to_string(&local).unwrap();
    assert!(saved.contains("python -m pytest *"), "{saved}");

    // No denies the call and stops the turn, as in Claude Code.
    let fetch = Ask::Permission {
        tool_name: "WebFetch".into(),
        input: json!({"url": "https://example.com"}),
        tool_use_id: None,
    };
    let answered = tokio::spawn({
        let spec = spec.clone();
        async move { ask(&spec, fetch).await }
    });
    let question = driver
        .until(|event| matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::Permission))
        .await;
    let AppEvent::Choice { choice } = question else {
        unreachable!()
    };
    assert_eq!(choice.title, "Let Claude Code use WebFetch?");
    driver
        .send(UiCommand::SetAside {
            to: AnswerTarget::Choice { id: choice.id },
        })
        .await;
    assert!(answered.await.unwrap().text.contains("\"deny\""));
    driver
        .until(|event| {
            matches!(
                conversation(event),
                Some(ConversationEvent::TurnCancelled { .. })
            )
        })
        .await;
    driver.exit().await;
}

fn permission(tool: &str, input: Value) -> Ask {
    Ask::Permission {
        tool_name: tool.into(),
        input,
        tool_use_id: None,
    }
}

/// A question open when Shift+Tab turns autopilot on doesn't wait for you: it gets the yes a
/// turn started on autopilot never has to ask for, and its closing line says so. The turn's
/// later questions are answered the same way with nothing shown, and what is asked about every
/// time gets a no the agent carries on from.
#[tokio::test]
async fn autopilot_coming_on_answers_the_open_question_and_the_ones_after() {
    let mut driver = TestDriver::start_with(captain_workflow_options(SUPERVISED)).await;
    driver
        .agent
        .push(FakeSession::completed(ANSWER).with_delay(Duration::from_secs(2)));
    driver.submit(TASK).await;
    let spec = first_spec(&driver).await;
    let edit = permission(
        "Edit",
        json!({"file_path": "invoice/money.py", "old_string": "sign = 1", "new_string": "x"}),
    );
    let answered = tokio::spawn({
        let spec = spec.clone();
        async move { ask(&spec, edit).await }
    });
    let question = driver
        .until(|event| matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::Permission))
        .await;
    let AppEvent::Choice { choice } = question else {
        unreachable!()
    };

    driver
        .send(UiCommand::ApprovalMode {
            mode: ApprovalMode::Autopilot,
        })
        .await;
    let reply = tokio::time::timeout(WAIT, answered)
        .await
        .expect("the open question was answered")
        .unwrap();
    assert!(reply.text.contains("\"allow\""), "{reply:?}");
    let closed = driver
        .until(|event| matches!(event, AppEvent::ChoiceClosed { id, .. } if id == &choice.id))
        .await;
    assert!(
        matches!(&closed, AppEvent::ChoiceClosed { outcome, .. }
            if outcome == "Decided on autopilot · yes to the edit to invoice/money.py"),
        "{closed:?}"
    );

    let tests = permission("Bash", json!({"command": "python -m pytest -q"}));
    assert!(ask(&spec, tests).await.text.contains("\"allow\""));
    let removal = permission("Bash", json!({"command": "rm -rf $BUILD_DIR/"}));
    let refused = ask(&spec, removal).await;
    assert!(refused.text.contains("\"deny\""), "{refused:?}");
    assert!(refused.text.contains("Carry on without it"), "{refused:?}");
    let own_files = permission(
        "Edit",
        json!({"file_path": ".argonauts/config.toml", "old_string": "a", "new_string": "b"}),
    );
    assert!(ask(&spec, own_files).await.text.contains("\"deny\""));

    // The no stopped nothing: the turn ends with the agent's answer.
    let ended = driver.until(turn_ended).await;
    assert!(
        matches!(
            conversation(&ended),
            Some(ConversationEvent::TurnFinished { .. })
        ),
        "{ended:?}"
    );
    let events = driver.exit().await;
    let asked = events
        .iter()
        .filter(|event| matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::Permission))
        .count();
    assert_eq!(asked, 1, "nothing was asked once autopilot was on");
}

/// Auto mode asks nothing: the session gets no approval tool, and no question comes.
#[tokio::test]
async fn auto_mode_asks_nothing() {
    let mut driver = TestDriver::start_with(captain_workflow_options("")).await;
    driver.agent.push(FakeSession::completed(ANSWER));
    driver.submit(TASK).await;
    driver.until(turn_ended).await;
    let spec = driver.agent.specs().remove(0);
    let events = driver.exit().await;
    assert!(
        spec.asking
            .as_ref()
            .is_none_or(|asking| asking.asks == Asks::Never),
        "{:?}",
        spec.asking
    );
    assert!(
        !events
            .iter()
            .any(|event| matches!(event, AppEvent::Choice { .. })),
    );
}

/// Autopilot asks nothing either: with its switch on, the session gets no approval tool though
/// `captain.asks` would have it ask as its CLI does, and no question comes.
#[tokio::test]
async fn autopilot_asks_nothing() {
    let mut driver = TestDriver::start_with(captain_workflow_options(
        "[approvals]\nautopilot = true\n[captain]\nasks = \"like_cli\"\n",
    ))
    .await;
    driver.agent.push(FakeSession::completed(ANSWER));
    driver.submit(TASK).await;
    driver.until(turn_ended).await;
    let spec = driver.agent.specs().remove(0);
    let events = driver.exit().await;
    assert!(
        spec.asking
            .as_ref()
            .is_none_or(|asking| asking.asks == Asks::Never),
        "{:?}",
        spec.asking
    );
    assert!(
        !events
            .iter()
            .any(|event| matches!(event, AppEvent::Choice { .. })),
    );
}

/// Running out mid-turn: Codex carries on the same request in the same folder, told what
/// changed, under a `↷` line naming both.
#[tokio::test]
async fn running_out_hands_the_turn_to_the_next_agent() {
    let mut options = captain_workflow_options("");
    options.flags = vec![r#"fallback.main.order=["codex"]"#.to_owned()];
    let mut driver = TestDriver::start_with(options).await;
    let codex = driver
        .directory
        .add(FakeRunner::cli("codex", "openai").then(FakeSession::completed(ANSWER)));
    driver.agent.respond(|spec: &SessionSpec| {
        std::fs::write(spec.workdir.join("invoice/money.py"), "half\n").unwrap();
        FakeSession::ended(EndReason::UsageLimit { resets_at: None })
    });
    driver.submit(TASK).await;
    let ended = driver.until(turn_ended).await;
    let events = driver.exit().await;
    assert!(matches!(
        conversation(&ended),
        Some(ConversationEvent::TurnFinished { reply: TurnReply::Answer { markdown }, .. }) if markdown == ANSWER
    ));
    let handed = events.iter().find_map(|event| match conversation(event) {
        Some(ConversationEvent::FellBack { from, to, told, .. }) => Some((from, to, told)),
        _ => None,
    });
    let (from, to, told) = handed.expect("a fallback line");
    assert_eq!(
        (from.agent.as_str(), to.agent.as_str()),
        ("claude-code", "codex")
    );
    assert!(told.contains("invoice/money.py changed"), "{told}");
    let spec = codex.specs().remove(0);
    assert_eq!(spec.access, Access::Direct);
    let note: String = spec
        .prompt
        .iter()
        .filter(|part| part.kind == InputPartKind::Fallback)
        .map(|part| part.text.clone())
        .collect();
    assert!(note.contains("invoice/money.py"), "{note}");
    let started = events
        .iter()
        .filter(|event| {
            matches!(
                conversation(event),
                Some(ConversationEvent::TurnStarted { .. })
            )
        })
        .count();
    assert_eq!(started, 1, "the turn goes on, it doesn't start again");
}

/// A sign-in that expired mid-turn falls back the same way, and the line says the CLI is
/// signed out and how to sign it in again rather than its raw error.
#[tokio::test]
async fn a_signed_out_cli_falls_back_and_says_how_to_sign_in() {
    let mut options = captain_workflow_options("");
    options.flags = vec![r#"fallback.main.order=["codex"]"#.to_owned()];
    let mut driver = TestDriver::start_with(options).await;
    driver
        .directory
        .add(FakeRunner::cli("codex", "openai").then(FakeSession::completed(ANSWER)));
    driver.agent.push(FakeSession::ended(EndReason::Auth {
        message: "Login expired · Please run /login".into(),
    }));
    driver.submit(TASK).await;
    driver.until(turn_ended).await;
    let events = driver.exit().await;
    let fell_back = events.iter().find_map(|event| match conversation(event) {
        Some(ConversationEvent::FellBack {
            why, signed_out, ..
        }) => Some((why, signed_out)),
        _ => None,
    });
    let (why, signed_out) = fell_back.expect("a fallback");
    assert_eq!(why, "is signed out (its sign-in expired)");
    assert_eq!(
        signed_out,
        &Some(argonauts_core::app::SignedOut {
            why: "its sign-in expired".into(),
            login: Some("claude /login".into()),
        })
    );
}

/// With `fallback.mode = "wait"` the turn ends the way the CLI ends it, with a line saying what
/// it changed.
#[tokio::test]
async fn with_fallback_off_the_turn_ends_and_says_what_changed() {
    let mut options = captain_workflow_options("[fallback]\nmode = \"wait\"\n");
    options.flags = vec![r#"fallback.main.order=["codex"]"#.to_owned()];
    let mut driver = TestDriver::start_with(options).await;
    let codex = driver.directory.add(FakeRunner::cli("codex", "openai"));
    driver.agent.respond(|spec: &SessionSpec| {
        std::fs::write(spec.workdir.join("invoice/money.py"), "half\n").unwrap();
        FakeSession::ended(EndReason::UsageLimit { resets_at: None })
    });
    driver.submit(TASK).await;
    driver.until(turn_ended).await;
    let stopped = driver
        .until(
            |event| matches!(event, AppEvent::Notice { text, .. } if text.starts_with("Stopped")),
        )
        .await;
    driver.exit().await;
    assert!(codex.specs().is_empty());
    let AppEvent::Notice { text, .. } = stopped else {
        unreachable!()
    };
    assert_eq!(
        text,
        "Stopped · invoice/money.py (+1 -1) changed · /rewind puts it back"
    );
}

/// A turn that loops is stopped by the repeat watchdog, as a run's session is: one line says
/// what it repeated, its edits stay, and no fallback takes the request.
#[tokio::test]
async fn a_looping_turn_is_stopped_with_a_line_and_no_fallback() {
    let mut options = captain_workflow_options("");
    options.flags = vec![r#"fallback.main.order=["codex"]"#.to_owned()];
    let mut driver = TestDriver::start_with(options).await;
    let root = driver.repo.root().to_owned();
    let codex = driver
        .directory
        .add(FakeRunner::cli("codex", "openai").then(FakeSession::completed(ANSWER)));
    driver.agent.respond(|spec: &SessionSpec| {
        std::fs::write(spec.workdir.join("invoice/money.py"), "half\n").unwrap();
        FakeSession::ended(EndReason::Stuck {
            watchdog: Watchdog::Repeat,
            calls: Some(CallCount {
                name: "execute".into(),
                times: 12,
            }),
        })
    });
    driver.submit(TASK).await;
    let ended = driver
        .until(|event| {
            matches!(
                conversation(event),
                Some(ConversationEvent::TurnStopped { .. } | ConversationEvent::TurnFailed { .. })
            )
        })
        .await;
    let kept = driver
        .until(|event| matches!(event, AppEvent::Notice { text, .. } if text.contains("/rewind")))
        .await;
    let spec = driver.agent.specs().remove(0);
    let money = read(&root, "invoice/money.py");
    let events = driver.exit().await;
    assert_eq!(money, "half\n", "its edit stays");
    assert_eq!(spec.limits.repeat_limit, Some(10));
    assert_eq!(spec.limits.inactivity_min, Some(15.0));
    let Some(ConversationEvent::TurnStopped { why, .. }) = conversation(&ended) else {
        panic!("the turn ends stopped, not failed: {ended:?}");
    };
    assert_eq!(
        why,
        "Stopped: Opus 5.5 repeated the same execute call 12 times. Its edits stay in your \
         checkout."
    );
    assert!(matches!(
        kept,
        AppEvent::Notice { text, .. } if text == "invoice/money.py (+1 -1) changed · /rewind puts it back"
    ));
    assert!(codex.specs().is_empty(), "no fallback");
    let fell_back = events.iter().any(|event| {
        matches!(
            conversation(event),
            Some(ConversationEvent::FellBack { .. })
        )
    });
    assert!(!fell_back);
}

/// A scratch file the turn made and left untracked is named at its end, so it doesn't hide
/// in your checkout. One that was there before the turn isn't the turn's.
#[tokio::test]
async fn a_turn_names_the_files_it_left_untracked() {
    let mut driver = TestDriver::start_with(captain_workflow_options("")).await;
    let root = driver.repo.root().to_owned();
    std::fs::write(root.join("notes.txt"), "yours\n").unwrap();
    driver.agent.respond(|spec: &SessionSpec| {
        std::fs::write(spec.workdir.join("invoice/money.py"), "negative = True\n").unwrap();
        std::fs::write(spec.workdir.join("test_money_fix.py"), "print(1)\n").unwrap();
        FakeSession::completed(ANSWER)
    });
    driver.submit(TASK).await;
    driver.until(turn_ended).await;
    let left = driver
        .until(|event| matches!(event, AppEvent::Notice { text, .. } if text.starts_with("Left")))
        .await;
    driver.exit().await;
    assert!(matches!(
        left,
        AppEvent::Notice { text, .. } if text == "Left untracked: test_money_fix.py"
    ));
}

/// `/rewind` lists the messages whose turns changed files and puts back what you pick.
#[tokio::test]
async fn rewind_puts_back_a_direct_turns_files() {
    let mut driver = TestDriver::start_with(captain_workflow_options("")).await;
    driver.agent.respond(fixing(Duration::ZERO));
    let root = driver.repo.root().to_owned();
    driver.submit(TASK).await;
    driver.until(turn_ended).await;
    assert_eq!(read(&root, "invoice/money.py"), "negative = True\n");

    driver
        .send(UiCommand::Slash {
            command: SlashCommand::Rewind { task: None },
        })
        .await;
    let question = driver
        .until(|event| matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::RewindTurn))
        .await;
    let AppEvent::Choice { choice } = question else {
        unreachable!()
    };
    assert_eq!(choice.options.len(), 1);
    let AnswerAction::Choose { value } = &choice.options[0].action else {
        panic!("{:?}", choice.options[0])
    };
    driver.send(choose(choice.id, value)).await;
    let closed = driver
        .until(|event| matches!(event, AppEvent::ChoiceClosed { .. }))
        .await;
    assert!(
        matches!(&closed, AppEvent::ChoiceClosed { outcome, .. } if outcome == "Put back invoice/money.py"),
        "{closed:?}"
    );
    assert_eq!(read(&root, "invoice/money.py"), "sign = 1\n");
    driver.exit().await;
}

/// agy can't ask in a headless run: the commands it was refused come after its answer, and
/// "Yes, and continue" resumes it for one turn that runs commands without asking.
#[tokio::test]
async fn agys_refused_commands_are_offered_after_its_answer() {
    let mut driver = TestDriver::start_with(captain_workflow_options(
        "crew.main = \"antigravity-cli\"\n[approvals.understand]\nmode = \"supervised\"\n",
    ))
    .await;
    let refused =
        FakeSession::completed("I couldn't run the tests: running a command needs approval.")
            .with_event(tool(
                "s2",
                "run_command",
                json!({"CommandLine": "python -m pytest -q"}),
            ))
            .with_event(RunnerEvent::Agent(AgentEvent::ToolFinished {
                id: "s2".into(),
                ok: false,
                output: Some(
                    "permission check failed for unsandboxed \"python -m pytest -q\"".into(),
                ),
                parent: None,
            }))
            .with_cli_session("conv-1");
    let agy = driver.directory.add(
        FakeRunner::cli("antigravity-cli", "google")
            .then(refused)
            .then(FakeSession::completed("6 passed.")),
    );
    driver.submit(TASK).await;
    driver.until(turn_ended).await;
    let question = driver
        .until(|event| matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::RefusedCommands))
        .await;
    let AppEvent::Choice { choice } = question else {
        unreachable!()
    };
    assert_eq!(choice.title, "Let agy run what it was refused?");
    assert_eq!(choice.body, ["python -m pytest -q"]);
    assert_eq!(
        agy.specs()[0].asking.as_ref().map(|a| a.asks),
        Some(Asks::LikeCli)
    );
    driver.send(choose(choice.id, "continue")).await;
    driver.until(turn_ended).await;
    driver.exit().await;
    let resumed = agy.specs().remove(1);
    assert_eq!(resumed.access, Access::Direct);
    assert_eq!(resumed.resume.as_deref(), Some("conv-1"));
    assert!(
        resumed
            .asking
            .as_ref()
            .is_none_or(|a| a.asks == Asks::Never)
    );
    assert_eq!(
        resumed.prompt[0].text,
        "You may run the commands you were refused."
    );
}

/// One of the main session's tools, called by the session of the turn in flight.
fn main_tool(name: &str, arguments: Value) -> Ask {
    Ask::Tool {
        name: name.to_owned(),
        arguments,
    }
}

const START_WORKFLOW: &str = "argonauts_start_workflow";

/// `argonauts_start_workflow` in Captain: refused when your message asked for no run, and
/// otherwise a run starts for your message as typed, with the instruction checks, so the run
/// says what was followed. A word picked out of your message starts nothing, and the agent's
/// own reading only ever follows your words, marked as its own.
#[tokio::test]
async fn in_captain_the_main_session_starts_a_run_only_when_you_asked_for_one() {
    let driver = TestDriver::start_with(captain_workflow_options("")).await;
    driver.directory.taking_tools("claude-code");
    driver.directory.add(FakeRunner::cli("codex", "openai"));
    driver
        .directory
        .add(FakeRunner::cli("antigravity-cli", "google"));
    driver
        .agent
        .push(FakeSession::completed(ANSWER).with_delay(Duration::from_secs(3)));
    let typed = "Fix the rounding in invoice/money.py. Have grok build it and gemini review it, \
                 and merge without asking me.";
    driver.submit(typed).await;
    let spec = first_spec(&driver).await;
    let asking = spec.asking.as_ref().expect("the turn listens");
    assert_eq!(
        asking.tools,
        [
            START_WORKFLOW,
            "argonauts_set_goal",
            "argonauts_setup",
            "argonauts_guide",
            "argonauts_lookup"
        ]
    );
    let standing = asking.standing.as_deref().expect("standing lines");
    assert!(
        standing.contains("`argonauts_start_workflow`"),
        "{standing}"
    );
    // Your message goes as you typed it, and the setup in use follows it once.
    assert_eq!(spec.prompt[0].text, typed);
    let setup = &spec.prompt.last().expect("the setup note").text;
    assert!(
        setup.contains("Argonauts Code setup: Captain is in use"),
        "{setup}"
    );

    // Words you didn't write, and a lone word picked out of your message, start nothing.
    for how_to_run in [
        vec![json!({"says": "use the whole crew", "kind": "crew"})],
        vec![json!({"says": "the", "kind": "mode", "value": "crew"})],
    ] {
        let unasked = ask(
            &spec,
            main_tool(
                START_WORKFLOW,
                json!({
                    "request": "Delete tests/test_money.py and rewrite the module from scratch",
                    "how_to_run": how_to_run,
                }),
            ),
        )
        .await;
        assert!(
            unasked.text.starts_with("No workflow started."),
            "{}",
            unasked.text
        );
        assert!(
            unasked.text.contains("What came of each instruction"),
            "{}",
            unasked.text
        );
    }
    assert!(driver.conductor.starts().is_empty());

    let asking = spec.clone();
    let asked = tokio::spawn(async move {
        let tool = main_tool(
            START_WORKFLOW,
            json!({
                "request": "Fix the rounding in invoice/money.py, where the sign comes late",
                "how_to_run": [
                    {"says": "have grok build it", "kind": "build", "who": "grok"},
                    {"says": "gemini review it", "kind": "review", "who": "gemini"},
                    {"says": "merge without asking me", "kind": "merge"},
                ],
            }),
        );
        ask(&asking, tool).await
    });
    // The answer waits until the run is under way.
    let run = super::main_session_tests::followed_run(&driver).await;
    let started = super::main_session_tests::agent_started(&run, 1);
    driver.conductor.push(&run, started).await;
    let asked = asked.await.unwrap();
    assert!(
        asked
            .text
            .starts_with("A captain run started on this, as the user asked."),
        "{asked:?}"
    );
    let conductor = driver.conductor.clone();
    let deadline = tokio::time::Instant::now() + WAIT;
    while conductor.starts().is_empty() {
        assert!(tokio::time::Instant::now() < deadline);
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
    let start = conductor.starts().remove(0);
    // Your message as you typed it comes first, and the agent's account is marked as its own.
    assert_eq!(
        start.request,
        format!(
            "{typed}\n\nFrom the conversation, as the main agent put it: Fix the rounding in \
             invoice/money.py, where the sign comes late"
        )
    );
    assert_eq!(start.mode, RunMode::Captain);
    assert!(
        start
            .captain_or_crew
            .as_ref()
            .is_some_and(|t| t.as_you_asked())
    );
    let outcome = |says: &str| {
        start
            .instructions
            .iter()
            .find(|instruction| instruction.says == says)
            .map(|instruction| instruction.outcome.clone())
            .unwrap_or_else(|| panic!("no {says:?} in {:#?}", start.instructions))
    };
    assert!(matches!(
        outcome("gemini review it"),
        InstructionOutcome::Followed { ref said, .. } if said == "agy reviews"
    ));
    assert!(matches!(
        outcome("have grok build it"),
        InstructionOutcome::NotFollowed { ref why } if why.contains("isn't installed")
            || why.starts_with("no agent here is called grok")
    ));
    assert!(matches!(
        outcome("merge without asking me"),
        InstructionOutcome::NotFollowed { ref why } if why.contains("is a safety setting")
    ));
    assert!(
        start
            .request_settings
            .iter()
            .any(|setting| setting == "roles.reviewer.models=[\"antigravity-cli\"]"),
        "{:?}",
        start.request_settings
    );
    assert!(
        start
            .request_settings
            .iter()
            .any(|setting| setting == "captain.review=true")
    );
    // One run a turn.
    let again = ask(
        &spec,
        main_tool(
            START_WORKFLOW,
            json!({
                "request": "",
                "how_to_run": [{"says": "gemini review it", "kind": "review", "who": "gemini"}],
            }),
        ),
    )
    .await;
    assert!(
        again.text.starts_with("A workflow already started"),
        "{again:?}"
    );
    // A tool nothing registers is an error the session can read, and starts nothing.
    let unknown = ask(&spec, main_tool("argonauts_nothing", json!({}))).await;
    assert!(unknown.is_error, "{unknown:?}");
    assert_eq!(driver.conductor.starts().len(), 1);
    driver.exit().await;
}

/// A main session that has the start tool is told when your words name a reviewer and ask for
/// no workflow, so it keeps the work and has it reviewed before it lands. Words that name
/// nobody add nothing to what it hears.
#[tokio::test]
async fn in_captain_a_reviewer_you_name_is_told_to_the_session_that_can_start_a_run() {
    let told = |spec: &SessionSpec| {
        spec.prompt
            .iter()
            .any(|part| part.text.contains("own words name who reviews"))
    };
    let mut driver = TestDriver::start_with(captain_workflow_options("")).await;
    driver.directory.taking_tools("claude-code");
    driver.directory.add(FakeRunner::cli("codex", "openai"));
    driver.agent.push(FakeSession::completed(ANSWER));
    driver
        .submit("Fix the money rounding in invoice/money.py with Codex as the reviewer.")
        .await;
    let spec = first_spec(&driver).await;
    assert_eq!(
        spec.access,
        Access::Direct,
        "the session still gets the turn"
    );
    assert!(told(&spec), "{:?}", spec.prompt);
    driver.until(turn_ended).await;
    driver.exit().await;

    let mut driver = TestDriver::start_with(captain_workflow_options("")).await;
    driver.directory.taking_tools("claude-code");
    driver.directory.add(FakeRunner::cli("codex", "openai"));
    driver.agent.push(FakeSession::completed(ANSWER));
    driver
        .submit("Fix the money rounding in invoice/money.py.")
        .await;
    let spec = first_spec(&driver).await;
    assert!(!told(&spec), "{:?}", spec.prompt);
    driver.until(turn_ended).await;
    driver.exit().await;
}

/// "Use a workflow for this, with Codex as the reviewer" in Captain starts the orchestrator's
/// workflow with Codex reviewing and the main agent planning and building, even when the
/// call puts the role in `who` and the CLI in `value`; the session hears what started and with
/// whom: Captain, as Claude Code's own, since Claude Code plans and builds.
#[tokio::test]
async fn in_captain_a_workflow_with_codex_as_the_reviewer_starts_with_codex_reviewing() {
    let mut driver = TestDriver::start_with(captain_workflow_options("")).await;
    driver.directory.taking_tools("claude-code");
    driver.directory.add(FakeRunner::cli("codex", "openai"));
    driver
        .agent
        .push(FakeSession::completed(ANSWER).with_delay(Duration::from_secs(3)));
    let typed = "Use a workflow for this, with Codex as the reviewer, and choose everything else \
                 yourself. Fix the money rounding in invoice/money.py.";
    driver.submit(typed).await;
    let spec = first_spec(&driver).await;
    let asking = spec.clone();
    let asked = tokio::spawn(async move {
        let tool = main_tool(
            START_WORKFLOW,
            json!({
                "request": "Fix the money rounding in invoice/money.py",
                "how_to_run": [
                    {"says": "Use a workflow for this", "kind": "mode"},
                    {"says": "with Codex as the reviewer", "kind": "review",
                     "who": "reviewer", "value": "Codex"},
                ],
            }),
        );
        ask(&asking, tool).await
    });
    let run = super::main_session_tests::followed_run(&driver).await;
    let started = super::main_session_tests::agent_started(&run, 1);
    driver.conductor.push(&run, started).await;
    let asked = asked.await.unwrap();
    assert!(
        asked
            .text
            .contains("Starting a workflow: Captain, as Claude Code's own, with **")
            && asked.text.contains("Codex** reviewing as you asked; **")
            && asked.text.contains("Claude Code** plans and builds."),
        "{asked:?}"
    );
    let start = driver.conductor.starts().remove(0);
    assert_eq!(start.mode, RunMode::Crew);
    let settings = &start.request_settings;
    for wanted in [
        "workflow=\"orchestrator\"",
        "crew.orchestrator=\"main\"",
        "roles.reviewer.models=[\"codex\"]",
    ] {
        assert!(
            settings.iter().any(|setting| setting == wanted),
            "{wanted}: {settings:?}"
        );
    }
    // The main agent builds, over the builders the check infers for a named reviewer.
    let builders = settings
        .iter()
        .rev()
        .find(|setting| setting.starts_with("roles.worker.models="));
    assert_eq!(
        builders.map(String::as_str),
        Some("roles.worker.models=[\"claude-code\"]"),
        "{settings:?}"
    );
    // The crew shown is the one that runs: the main session builds, Codex reviews.
    let crew = driver
        .until(|event| {
            matches!(event, AppEvent::Notice { text, .. } if text.starts_with("Crew for this request"))
        })
        .await;
    let AppEvent::Notice { text, .. } = crew else {
        unreachable!()
    };
    let workers = text.lines().find(|line| line.starts_with("workers"));
    assert!(
        workers.is_some_and(|line| line.ends_with("your main session")),
        "{text}"
    );
    let reviewers = text.lines().find(|line| line.starts_with("reviewers"));
    assert!(
        reviewers.is_some_and(|line| line.contains("Codex") && line.ends_with("as you asked")),
        "{text}"
    );
    driver.exit().await;
}

/// Inside a crew workflow, a Captain the Captain-or-crew rules pick is checked by default. With
/// `captain_or_crew.captain_kind = "direct"` the session that planned it goes ahead in your
/// checkout.
#[tokio::test]
async fn a_captain_the_rules_pick_runs_direct_only_when_its_kind_says_so() {
    let small = json!({
        "task_type": "bugfix",
        "summary": "Fix the rounding",
        "files_likely": ["invoice/money.py"],
        "file_count": 1,
        "risk_labels": [],
        "tests_exist": true,
        "unknowns": []
    });
    let change = || {
        FakeSession::structured(json!({
            "kind": "change",
            "answer_markdown": "The sign is applied too late.",
            "estimate": small.clone()
        }))
        .with_cli_session("estimate-1")
    };
    let styled = |config: &'static str| CliOptions {
        prepare: Some(Box::new(move |repo: &argonauts_testkit::TempRepo| {
            std::fs::write(repo.global_config(), config).unwrap();
        })),
        ..CliOptions::default()
    };

    let mut driver =
        TestDriver::start_with(styled("[captain_or_crew]\ncaptain_kind = \"direct\"\n")).await;
    driver.agent.push(change());
    driver.agent.push(FakeSession::completed(ANSWER));
    driver.submit(TASK).await;
    driver.until(turn_ended).await;
    driver.until(turn_ended).await;
    let conductor = driver.conductor.clone();
    let specs = driver.agent.specs();
    let seen = driver.exit().await;
    assert!(conductor.starts().is_empty());
    assert_eq!(specs[1].access, Access::Direct);
    assert_eq!(specs[1].resume.as_deref(), Some("estimate-1"));
    assert_eq!(specs[1].prompt[0].text, "Go ahead.");
    // The turn is your request, shown once: the one going ahead continues the estimate's.
    let started: Vec<(String, bool)> = seen
        .iter()
        .filter_map(|event| match conversation(event) {
            Some(ConversationEvent::TurnStarted {
                text, continues, ..
            }) => Some((text.clone(), *continues)),
            _ => None,
        })
        .collect();
    assert_eq!(started, [(TASK.to_owned(), false), (TASK.to_owned(), true)]);
    // The estimate's reply carries the start line of a Captain in your checkout.
    assert!(seen.iter().any(|event| matches!(
        conversation(event),
        Some(ConversationEvent::TurnFinished {
            reply: TurnReply::Change { captain_or_crew, .. },
            ..
        }) if captain_or_crew.captain == Some(argonauts_core::settings::protocol::CaptainKind::Direct)
    )));

    let mut driver = TestDriver::start().await;
    driver.agent.push(change());
    driver.submit(TASK).await;
    driver.until(turn_ended).await;
    let conductor = driver.conductor.clone();
    let deadline = tokio::time::Instant::now() + WAIT;
    while conductor.starts().is_empty() {
        assert!(tokio::time::Instant::now() < deadline);
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
    assert_eq!(conductor.starts()[0].mode, RunMode::Captain);
    assert_eq!(driver.agent.specs().len(), 1);
    driver.exit().await;
}

/// In a direct conversation a CLI command works in your checkout, as `/init` does in Claude
/// Code, with the command alone as its prompt.
#[tokio::test]
async fn a_cli_command_in_a_direct_conversation_works_in_your_checkout() {
    use argonauts_core::cli_commands::{CliCommand, CommandKind, CommandSource};

    let (mut parts, _) =
        crate::controller::test_support::TestCtx::new(captain_workflow_options(""));
    parts.agent.push(FakeSession::completed("Wrote CLAUDE.md."));
    let mut conversation = super::ConversationState::new(&parts.ctx).unwrap();
    let init = CliCommand {
        name: "init".into(),
        aliases: Vec::new(),
        args: String::new(),
        help: "Write CLAUDE.md".into(),
        kind: CommandKind::Cli,
        source: CommandSource::BuiltIn,
    };
    super::cli_command(&mut parts.ctx, &mut conversation, &init, "", "/init".into()).unwrap();
    let deadline = tokio::time::Instant::now() + WAIT;
    while parts.agent.specs().is_empty() {
        assert!(tokio::time::Instant::now() < deadline);
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
    let spec = parts.agent.specs().remove(0);
    assert_eq!(spec.access, Access::Direct);
    assert_eq!(spec.prompt.len(), 1);
    assert_eq!(spec.prompt[0].text, "/init");
}

/// `captain.asks = "every_change"` with a CLI that can't ask before each edit runs checked, and
/// says why.
#[tokio::test]
async fn every_change_with_codex_runs_in_a_checked_worktree() {
    let mut driver = TestDriver::start_with(captain_workflow_options(
        "crew.main = \"codex\"\n[approvals.understand]\nmode = \"supervised\"\n[captain]\nasks = \"every_change\"\n",
    ))
    .await;
    let codex = driver.directory.add(FakeRunner::cli("codex", "openai"));
    driver.submit(TASK).await;
    let notice = driver
        .until(
            |event| matches!(event, AppEvent::Notice { text, .. } if text.contains("checked worktree")),
        )
        .await;
    let conductor = driver.conductor.clone();
    let deadline = tokio::time::Instant::now() + WAIT;
    while conductor.starts().is_empty() {
        assert!(tokio::time::Instant::now() < deadline);
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
    driver.exit().await;
    assert!(matches!(
        notice,
        AppEvent::Notice { text, .. }
            if text == "Codex can't ask before each edit in a headless run, so this runs in a checked worktree."
    ));
    assert_eq!(conductor.starts()[0].mode, RunMode::Captain);
    assert!(codex.specs().is_empty());
}

/// Esc stops a direct turn: what it changed so far stays, and a line names it and `/rewind`.
#[tokio::test]
async fn esc_keeps_the_edits_and_says_how_to_put_them_back() {
    let mut driver = TestDriver::start_with(captain_workflow_options("")).await;
    driver.agent.respond(|spec: &SessionSpec| {
        std::fs::write(spec.workdir.join("invoice/money.py"), "half\n").unwrap();
        FakeSession::until_stopped(vec![tool(
            "t1",
            "Edit",
            json!({"file_path": "invoice/money.py"}),
        )])
    });
    driver.submit(TASK).await;
    first_spec(&driver).await;
    driver
        .until(|event| matches!(conversation(event), Some(ConversationEvent::Agent { .. })))
        .await;
    driver.send(UiCommand::CancelTurn).await;
    driver
        .until(|event| {
            matches!(
                conversation(event),
                Some(ConversationEvent::TurnCancelled { .. })
            )
        })
        .await;
    let line = driver
        .until(|event| matches!(event, AppEvent::Notice { text, .. } if text.contains("/rewind")))
        .await;
    let root = driver.repo.root().to_owned();
    assert_eq!(read(&root, "invoice/money.py"), "half\n");
    driver.exit().await;
    assert!(matches!(
        line,
        AppEvent::Notice { text, .. } if text == "invoice/money.py (+1 -1) changed · /rewind puts it back"
    ));
}

/// Plan first in the Captain workflow: `/plan <task>`, and a message while plan first is on, each
/// run a read-only turn that ends with its plan. Nothing changes until "Go ahead with this plan?"
/// is answered Yes, which resumes the session that planned, in your checkout.
#[tokio::test]
async fn plan_first_in_direct_captain_changes_nothing_until_you_go_ahead() {
    for by_command in [true, false] {
        let mut driver = TestDriver::start_with(captain_workflow_options("")).await;
        let root = driver.repo.root().to_owned();
        driver.agent.respond(|spec: &SessionSpec| {
            if spec.access == Access::Direct {
                std::fs::write(spec.workdir.join("invoice/money.py"), "negative = True\n").unwrap();
                FakeSession::completed(ANSWER)
            } else {
                FakeSession::completed("1. Read the sign first.\n2. Apply it once.")
                    .with_cli_session("plan-1")
            }
        });
        if by_command {
            driver
                .send(UiCommand::Slash {
                    command: SlashCommand::Plan {
                        task: Some(TASK.into()),
                    },
                })
                .await;
        } else {
            driver
                .send(UiCommand::Slash {
                    command: SlashCommand::Plan { task: None },
                })
                .await;
            driver.submit(TASK).await;
        }
        let question = driver
            .until(|event| {
                matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::GoAhead)
            })
            .await;
        let AppEvent::Choice { choice } = question else {
            unreachable!()
        };
        assert_eq!(choice.title, "Go ahead with this plan?");
        let specs = driver.agent.specs();
        assert_eq!(specs.len(), 1, "{by_command}");
        assert_eq!(specs[0].access, Access::ReadOnly);
        assert!(
            specs[0]
                .prompt
                .iter()
                .any(|part| part.text.contains("Plan first is on")),
            "{:?}",
            specs[0].prompt
        );
        assert_eq!(read(&root, "invoice/money.py"), "sign = 1\n");
        assert!(driver.conductor.starts().is_empty());

        driver.send(choose(choice.id, "yes")).await;
        driver
            .until(|event| {
                matches!(
                    conversation(event),
                    Some(ConversationEvent::TurnFinished {
                        reply: TurnReply::Answer { markdown },
                        ..
                    }) if markdown == ANSWER
                )
            })
            .await;
        let specs = driver.agent.specs();
        assert_eq!(specs[1].access, Access::Direct);
        assert_eq!(specs[1].resume.as_deref(), Some("plan-1"));
        assert_eq!(specs[1].prompt[0].text, "Go ahead with this plan.");
        assert_eq!(read(&root, "invoice/money.py"), "negative = True\n");
        assert!(driver.conductor.starts().is_empty());
        driver.exit().await;
    }
}

/// The fallback question: with `fallback.mode = "ask"`, and in auto mode when the only one left is
/// a paid API, a direct turn that runs out asks who carries it on, from the shortlist a run's task
/// would get. Your pick carries it on; Stop ends it with a line saying what changed.
#[tokio::test]
async fn running_out_asks_who_carries_it_on_when_it_should() {
    use std::sync::Arc;

    use argonauts_core::registry::{ModelEntry, ModelRegistry};
    use argonauts_testkit::services::StaticRegistry;

    let api_key = || -> Arc<dyn ModelRegistry> {
        let registry = StaticRegistry::default();
        registry.add(
            serde_json::from_value::<ModelEntry>(json!({
                "id": "codex",
                "provider": "openai",
                "kind": "cli",
                "access": "api-key",
                "cost": { "unit": "usd", "input_per_mtok": 1.0, "output_per_mtok": 4.0 },
            }))
            .unwrap(),
        );
        Arc::new(registry)
    };
    for (config, registry, pick) in [
        ("[fallback]\nmode = \"ask\"\n", None, "codex"),
        ("", Some(api_key()), "stop"),
    ] {
        let mut options = captain_workflow_options(config);
        options.flags = vec![r#"fallback.main.order=["codex"]"#.to_owned()];
        options.registry = registry;
        let mut driver = TestDriver::start_with(options).await;
        let codex = driver
            .directory
            .add(FakeRunner::cli("codex", "openai").then(FakeSession::completed(ANSWER)));
        driver.agent.respond(|spec: &SessionSpec| {
            std::fs::write(spec.workdir.join("invoice/money.py"), "half\n").unwrap();
            FakeSession::ended(EndReason::UsageLimit { resets_at: None })
        });
        driver.submit(TASK).await;
        let question = driver
            .until(|event| {
                matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::Fallback)
            })
            .await;
        let AppEvent::Choice { choice } = question else {
            unreachable!()
        };
        assert!(
            choice.title.ends_with("Who carries it on?"),
            "{}",
            choice.title
        );
        let keys: Vec<char> = choice.options.iter().map(|option| option.key).collect();
        assert_eq!(keys, ['1', 's'], "{pick}");
        // Nothing carried on before you answered.
        assert!(codex.specs().is_empty(), "{pick}");
        if registry_is_paid(&choice) {
            assert_eq!(
                choice.options[0].detail.as_deref(),
                Some("an API key, billed to your account")
            );
        }
        let value = match pick {
            "stop" => "stop".to_owned(),
            _ => "codex".to_owned(),
        };
        driver.send(choose(choice.id, &value)).await;
        let ended = driver.until(turn_ended).await;
        driver.exit().await;
        match pick {
            "stop" => {
                assert!(matches!(
                    conversation(&ended),
                    Some(ConversationEvent::TurnFailed { .. })
                ));
                assert!(codex.specs().is_empty());
            }
            _ => {
                assert!(matches!(
                    conversation(&ended),
                    Some(ConversationEvent::TurnFinished { reply: TurnReply::Answer { markdown }, .. })
                        if markdown == ANSWER
                ));
                assert_eq!(codex.specs()[0].access, Access::Direct);
            }
        }
    }
}

fn registry_is_paid(choice: &argonauts_core::app::AppChoice) -> bool {
    choice
        .options
        .first()
        .and_then(|option| option.detail.as_deref())
        .is_some_and(|detail| detail.contains("API key"))
}

/// Ignored files a turn writes: nothing kept how they were, so the turn's line and `/rewind`
/// list them as ones it can't put back, and `/rewind` never removes them. The tracked file goes
/// back.
/// With our sandbox off, a shell command that writes Argonauts Code's own files has what it named
/// put back too. A file it didn't name is only said.
#[tokio::test]
async fn a_shell_command_that_writes_argonauts_own_files_is_put_back_too() {
    let options = CliOptions {
        prepare: Some(Box::new(|repo: &argonauts_testkit::TempRepo| {
            repo.write(".argonauts/config.toml", "workflow = \"captain\"\n")
                .unwrap();
            repo.write(".argonauts/notes.md", "mine\n").unwrap();
            repo.commit_all("start").unwrap();
            std::fs::write(
                repo.global_config(),
                "[captain_or_crew]\nforce = \"captain\"\n[sandbox]\nmode = \"tool\"\n",
            )
            .unwrap();
        })),
        ..CliOptions::default()
    };
    let mut driver = TestDriver::start_with(options).await;
    let root = driver.repo.root().to_owned();
    driver.agent.respond(|spec: &SessionSpec| {
        let root = &spec.workdir;
        std::fs::write(root.join(".argonauts/config.toml"), "workflow = \"x\"\n").unwrap();
        std::fs::write(root.join(".argonauts/notes.md"), "a script's\n").unwrap();
        FakeSession::completed(ANSWER).with_event(tool(
            "t1",
            "Bash",
            json!({"command": "cd .argonauts && sed -i '' s/captain/x/ config.toml"}),
        ))
    });
    driver.submit("Point the config at x.").await;
    driver.until(turn_ended).await;
    driver
        .until(|event| {
            matches!(event, AppEvent::Notice { text, .. }
                if text.starts_with("This turn edited .argonauts/config.toml, which only a setup"))
        })
        .await;
    assert_eq!(
        read(&root, ".argonauts/config.toml"),
        "workflow = \"captain\"\n"
    );
    // Nothing named it, so it stays, and a line says it changed.
    assert_eq!(read(&root, ".argonauts/notes.md"), "a script's\n");
    driver.exit().await;
}

/// With our sandbox off, an edit the main session made to Argonauts Code's own files goes back when
/// its turn ends, and a line says so: a setup changes them.
#[tokio::test]
async fn an_edit_to_argonauts_own_files_goes_back_when_our_sandbox_is_off() {
    let options = CliOptions {
        prepare: Some(Box::new(|repo: &argonauts_testkit::TempRepo| {
            repo.write(".argonauts/notes.md", "mine\n").unwrap();
            repo.write("app.py", "print(1)\n").unwrap();
            repo.commit_all("start").unwrap();
            std::fs::write(
                repo.global_config(),
                "[captain_or_crew]\nforce = \"captain\"\n[sandbox]\nmode = \"tool\"\n",
            )
            .unwrap();
        })),
        ..CliOptions::default()
    };
    let mut driver = TestDriver::start_with(options).await;
    let root = driver.repo.root().to_owned();
    driver.agent.respond(|spec: &SessionSpec| {
        let root = &spec.workdir;
        std::fs::write(root.join(".argonauts/notes.md"), "the model's\n").unwrap();
        std::fs::write(root.join("app.py"), "print(2)\n").unwrap();
        FakeSession::completed(ANSWER)
            .with_event(tool(
                "t1",
                "Write",
                json!({"file_path": ".argonauts/notes.md"}),
            ))
            .with_event(changed(".argonauts/notes.md"))
            .with_event(tool("t2", "Edit", json!({"file_path": "app.py"})))
            .with_event(changed("app.py"))
    });
    driver.submit("Print 2, and note it.").await;
    driver.until(turn_ended).await;
    let told = driver
        .until(|event| {
            matches!(event, AppEvent::Notice { text, .. }
                if text.starts_with("This turn edited .argonauts/notes.md, which only a setup changes"))
        })
        .await;
    assert!(matches!(told, AppEvent::Notice { .. }));
    assert_eq!(read(&root, ".argonauts/notes.md"), "mine\n");
    assert_eq!(read(&root, "app.py"), "print(2)\n");
    driver.exit().await;
}

#[tokio::test]
async fn rewind_lists_the_ignored_files_a_turn_wrote_and_leaves_them() {
    let options = CliOptions {
        prepare: Some(Box::new(|repo: &argonauts_testkit::TempRepo| {
            repo.write(".gitignore", ".env\nconfig/local.toml\n")
                .unwrap();
            repo.write("app.py", "print(1)\n").unwrap();
            repo.commit_all("start").unwrap();
            repo.write(".env", "TOKEN=yours\n").unwrap();
            std::fs::write(
                repo.global_config(),
                "[captain_or_crew]\nforce = \"captain\"\n",
            )
            .unwrap();
        })),
        ..CliOptions::default()
    };
    let mut driver = TestDriver::start_with(options).await;
    let root = driver.repo.root().to_owned();
    driver.agent.respond(|spec: &SessionSpec| {
        let root = &spec.workdir;
        std::fs::write(root.join(".env"), "TOKEN=changed-by-agent\n").unwrap();
        std::fs::create_dir_all(root.join("config")).unwrap();
        std::fs::write(root.join("config/local.toml"), "debug = true\n").unwrap();
        std::fs::write(root.join("app.py"), "print(2)\n").unwrap();
        let env = root.join(".env").to_string_lossy().into_owned();
        FakeSession::completed(ANSWER)
            .with_event(tool("t1", "Write", json!({"file_path": env})))
            .with_event(changed(&env))
            .with_event(tool(
                "t2",
                "Write",
                json!({"file_path": "config/local.toml"}),
            ))
            .with_event(changed("config/local.toml"))
            .with_event(tool("t3", "Edit", json!({"file_path": "app.py"})))
            .with_event(changed("app.py"))
    });
    driver.submit("Turn on debug and print 2.").await;
    driver.until(turn_ended).await;

    driver
        .send(UiCommand::Slash {
            command: SlashCommand::Rewind { task: None },
        })
        .await;
    let question = driver
        .until(|event| matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::RewindTurn))
        .await;
    let AppEvent::Choice { choice } = question else {
        unreachable!()
    };
    assert_eq!(choice.options[0].detail.as_deref(), Some("3 files"));
    let AnswerAction::Choose { value } = &choice.options[0].action else {
        panic!("{:?}", choice.options[0])
    };
    driver.send(choose(choice.id, value)).await;
    let closed = driver
        .until(|event| matches!(event, AppEvent::ChoiceClosed { .. }))
        .await;
    let AppEvent::ChoiceClosed { outcome, .. } = closed else {
        unreachable!()
    };
    assert_eq!(
        outcome,
        "Put back app.py · can't put back, as nothing kept how they were: .env, \
         config/local.toml"
    );
    assert_eq!(read(&root, "app.py"), "print(1)\n");
    assert_eq!(read(&root, ".env"), "TOKEN=changed-by-agent\n");
    assert_eq!(read(&root, "config/local.toml"), "debug = true\n");
    driver.exit().await;
}

/// Whatever a CLI calls its write, the turn's record has the file, so `/rewind` names an
/// ignored one it can't put back: Codex's file_change and agy's sed_file included.
#[tokio::test]
async fn rewind_names_the_ignored_files_each_cli_wrote() {
    let writers = [
        "claude-code",
        "codex",
        "agy write_to_file",
        "agy sed_file",
        "opencode",
    ];
    let options = CliOptions {
        prepare: Some(Box::new(|repo: &argonauts_testkit::TempRepo| {
            repo.write(".gitignore", "notes/\n").unwrap();
            repo.write("app.py", "print(1)\n").unwrap();
            repo.commit_all("start").unwrap();
            std::fs::write(
                repo.global_config(),
                "[captain_or_crew]\nforce = \"captain\"\n",
            )
            .unwrap();
        })),
        ..CliOptions::default()
    };
    let mut driver = TestDriver::start_with(options).await;
    let root = driver.repo.root().to_owned();
    driver.agent.respond(move |spec: &SessionSpec| {
        let root = &spec.workdir;
        std::fs::write(root.join("app.py"), "print(2)\n").unwrap();
        std::fs::create_dir_all(root.join("notes")).unwrap();
        let session = FakeSession::completed(ANSWER)
            .with_event(tool("t1", "Edit", json!({"file_path": "app.py"})))
            .with_event(changed("app.py"));
        writers.iter().fold(session, |session, writer| {
            let path = root.join(format!("notes/{}.md", writer.replace(' ', "-")));
            std::fs::write(&path, "hi\n").unwrap();
            written_by(writer, &path)
                .into_iter()
                .fold(session, |session, event| {
                    session.with_event(RunnerEvent::Agent(event))
                })
        })
    });
    driver.submit("Print 2, and take notes.").await;
    driver.until(turn_ended).await;

    driver
        .send(UiCommand::Slash {
            command: SlashCommand::Rewind { task: None },
        })
        .await;
    let AppEvent::Choice { choice } = driver
        .until(|event| matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::RewindTurn))
        .await
    else {
        unreachable!()
    };
    let AnswerAction::Choose { value } = &choice.options[0].action else {
        panic!("{:?}", choice.options[0])
    };
    driver.send(choose(choice.id, value)).await;
    let AppEvent::ChoiceClosed { outcome, .. } = driver
        .until(|event| matches!(event, AppEvent::ChoiceClosed { .. }))
        .await
    else {
        unreachable!()
    };
    assert_eq!(
        outcome,
        "Put back app.py · can't put back, as nothing kept how they were: \
         notes/agy-sed_file.md, notes/agy-write_to_file.md, notes/claude-code.md, \
         notes/codex.md, notes/opencode.md"
    );
    assert_eq!(read(&root, "app.py"), "print(1)\n");
    driver.exit().await;
}

/// A protected file a turn made where the sandbox couldn't hold it, as on Linux or in a
/// container, is set aside in the turn's own folder, where nothing loads it, and a line says so.
#[tokio::test]
async fn a_protected_file_a_turn_planted_is_set_aside() {
    let mut driver = TestDriver::start_with(captain_workflow_options("")).await;
    let root = driver.repo.root().to_owned();
    driver.agent.respond(|spec: &SessionSpec| {
        std::fs::write(
            spec.workdir.join(".mcp.json"),
            r#"{"mcpServers": {"x": {"command": "sh"}}}"#,
        )
        .unwrap();
        std::fs::write(spec.workdir.join("invoice/money.py"), "negative = True\n").unwrap();
        FakeSession::completed(ANSWER)
    });
    driver.submit(TASK).await;
    let notice = driver
        .until(|event| {
            matches!(event, AppEvent::Notice { text, .. } if text.starts_with("This turn made .mcp.json"))
        })
        .await;
    let AppEvent::Notice { text, .. } = notice else {
        unreachable!()
    };
    assert!(!root.join(".mcp.json").exists());
    assert_eq!(read(&root, "invoice/money.py"), "negative = True\n");
    let aside = text
        .split(" set aside in ")
        .nth(1)
        .and_then(|rest| rest.split(" where").next())
        .expect("where it went");
    assert!(Path::new(aside).join(".mcp.json").is_file(), "{text}");
    driver.exit().await;
}

/// Claude Code sends nothing while its question waits for your answer (live, 2.1.289), and that
/// silence isn't shown as a stall. Without a question open, a stall still shows.
#[tokio::test]
async fn a_question_waiting_on_you_is_no_stall() {
    use argonauts_core::event::ErrorCategory;

    let stalled = || {
        RunnerEvent::Agent(AgentEvent::Error {
            category: ErrorCategory::Stalled,
            message: "Claude Code has sent nothing for 30 seconds, not even its heartbeat".into(),
            retryable: true,
        })
    };
    let shows_a_stall = |events: &[AppEvent]| {
        events.iter().any(|event| {
            matches!(
                conversation(event),
                Some(ConversationEvent::Agent {
                    event: AgentEvent::Error {
                        category: ErrorCategory::Stalled,
                        ..
                    },
                    ..
                })
            )
        })
    };
    for question_open in [true, false] {
        let mut driver = TestDriver::start_with(captain_workflow_options(SUPERVISED)).await;
        driver.agent.push(
            FakeSession::completed(ANSWER)
                .with_event(stalled())
                .with_delay(Duration::from_millis(800)),
        );
        driver.submit(TASK).await;
        let spec = first_spec(&driver).await;
        if question_open {
            let edit = Ask::Permission {
                tool_name: "Edit".into(),
                input: json!({"file_path": "invoice/money.py"}),
                tool_use_id: None,
            };
            tokio::spawn(async move { ask(&spec, edit).await });
            driver
                .until(|event| {
                    matches!(event, AppEvent::Choice { choice } if choice.kind == ChoiceKind::Permission)
                })
                .await;
        }
        driver.until(turn_ended).await;
        let events = driver.exit().await;
        assert_eq!(
            shows_a_stall(&events),
            !question_open,
            "question open: {question_open}"
        );
    }
}

/// The Captain workflow sends what you type to the main session, but a command that names a run
/// still starts it: `/workflow` starts a crew run and never becomes a direct turn, since
/// commands come first. `/goal` names no run: it sets a condition, and starts nothing.
#[tokio::test]
async fn under_the_captain_workflow_workflow_starts_its_run_and_goal_starts_nothing() {
    let driver = TestDriver::start_with(captain_workflow_options("")).await;
    driver
        .send(UiCommand::Slash {
            command: SlashCommand::Goal {
                text: Some("every test passes".to_owned()),
            },
        })
        .await;
    driver
        .send(UiCommand::Slash {
            command: SlashCommand::WorkflowRun {
                task: Some("fix the typo in the README".to_owned()),
            },
        })
        .await;
    let conductor = driver.conductor.clone();
    let deadline = tokio::time::Instant::now() + WAIT;
    while conductor.starts().is_empty() {
        assert!(
            tokio::time::Instant::now() < deadline,
            "/workflow started no run"
        );
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
    let starts = conductor.starts();
    let [start] = starts.as_slice() else {
        panic!("one run, the workflow's: {starts:?}");
    };
    assert_eq!(start.mode, RunMode::Crew);
    assert_eq!(start.request, "fix the typo in the README");
    // The run carries the goal set before it.
    assert!(
        start
            .overrides
            .contains(&"goal.until=\"every test passes\"".to_owned()),
        "{:?}",
        start.overrides
    );
    assert!(driver.agent.specs().is_empty(), "no direct turn");
    driver.exit().await;
}