errand-bot 0.1.0

Run a coding agent from a chat channel, in a sandbox it cannot escape.
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
//! Daemon wiring tests, ported from `daemon_test.ts`.

use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use serde_json::json;
use tokio::sync::watch;

use super::{
    Daemon, DaemonOptions, SlashCommand, StartError, create_sandbox, inert_settings,
    render_startup_report,
};
use crate::agent::client::AgentProcess;
use crate::chat::inbound::{InboundDecision, RawMessage};
use crate::config::schema::Config;
use crate::config::schema::SandboxBackend;
use crate::config::validate::validate_config;
use crate::log::{LogFields, LogLevel, Logger};
use crate::memory::store::{MemoryStore, Scope};
use crate::sandbox::Backend;
use crate::sandbox::backend::{
    CapabilityReport, SandboxLaunch, SandboxLaunchError, SandboxUnavailableError,
};
use crate::sandbox::paths;
use crate::session::event::EndReason;
use crate::session::event::SessionEvent;
use crate::session::manager::{CreatedThread, FoundView, MadeThread, SandboxPool, ThreadFactory};
use crate::session::session::IncomingMessage;
use crate::session::session::RunningBox;
use crate::session::views::SessionView;
use crate::session::views::ViewError;

const OWNER: &str = "100000000000000001";

fn silent() -> Logger {
    Logger::new(LogFields::new(), Arc::new(|_level, _line| {}))
}

/// An agent that answers its readiness call and otherwise says nothing.
struct QuietAgent {
    queue: Mutex<std::collections::VecDeque<u8>>,
    closed: Mutex<bool>,
    exit: watch::Receiver<Option<i32>>,
}

#[derive(Clone)]
struct QuietControls {
    fake: Arc<QuietAgent>,
    sender: Arc<Mutex<Option<watch::Sender<Option<i32>>>>>,
}

impl QuietAgent {
    fn new() -> (Arc<Self>, QuietControls) {
        let (exit_sender, exit_receiver) = watch::channel(None);
        let fake = Arc::new(Self {
            queue: Mutex::new(std::collections::VecDeque::new()),
            closed: Mutex::new(false),
            exit: exit_receiver.clone(),
        });
        (
            Arc::clone(&fake),
            QuietControls {
                fake,
                sender: Arc::new(Mutex::new(Some(exit_sender))),
            },
        )
    }
}

impl QuietControls {
    fn end(&self) {
        {
            let mut closed = self.fake.closed.lock().unwrap();
            if *closed {
                return;
            }
            *closed = true;
        }
        self.fake.queue.lock().unwrap().clear();
        if let Some(sender) = self.sender.lock().unwrap().take() {
            let _ = sender.send(Some(0));
        }
    }
}

impl AgentProcess for QuietAgent {
    fn write(&self, bytes: &[u8]) -> std::io::Result<()> {
        let parsed: serde_json::Value = serde_json::from_slice(bytes).expect("a written command");
        if let Some(id) = parsed.get("id") {
            self.queue.lock().unwrap().extend(
                json!({ "type": "response", "id": id })
                    .to_string()
                    .into_bytes(),
            );
            self.queue.lock().unwrap().push_back(b'\n');
        }
        Ok(())
    }

    fn read_stdout<'a>(
        &'a self,
        buf: &'a mut [u8],
    ) -> Pin<Box<dyn Future<Output = std::io::Result<usize>> + Send + 'a>> {
        Box::pin(async move {
            loop {
                {
                    let mut queue = self.queue.lock().unwrap();
                    let count = queue.len().min(buf.len());
                    if count > 0 {
                        for (index, byte) in queue.drain(..count).enumerate() {
                            buf[index] = byte;
                        }
                        return Ok(count);
                    }
                    if *self.closed.lock().unwrap() {
                        return Ok(0);
                    }
                }
                tokio::time::sleep(Duration::from_millis(1)).await;
            }
        })
    }

    fn read_stderr<'a>(
        &'a self,
        _buf: &'a mut [u8],
    ) -> Pin<Box<dyn Future<Output = std::io::Result<usize>> + Send + 'a>> {
        Box::pin(async { Ok(0) })
    }

    fn exited(&self) -> Pin<Box<dyn Future<Output = Option<i32>> + Send>> {
        let mut receiver = self.exit.clone();
        Box::pin(async move {
            let _ = receiver.changed().await;
            *receiver.borrow()
        })
    }
}

struct FakeSandbox {
    report: Mutex<Option<CapabilityReport>>,
    probe_fails: Mutex<bool>,
    launched: Mutex<Vec<SandboxLaunch>>,
    agents: Mutex<Vec<QuietControls>>,
}

impl FakeSandbox {
    fn new(report: Option<CapabilityReport>) -> Arc<Self> {
        Arc::new(Self {
            report: Mutex::new(report),
            probe_fails: Mutex::new(false),
            launched: Mutex::new(Vec::new()),
            agents: Mutex::new(Vec::new()),
        })
    }
}

impl SandboxPool for FakeSandbox {
    fn probe(
        &self,
    ) -> Pin<Box<dyn Future<Output = Result<CapabilityReport, SandboxUnavailableError>> + Send + '_>>
    {
        if *self.probe_fails.lock().unwrap() {
            return Box::pin(async move {
                Err(SandboxUnavailableError {
                    backend: SandboxBackend::Bailey,
                    reasons: vec!["broken".to_owned()],
                })
            });
        }
        let report = self
            .report
            .lock()
            .unwrap()
            .clone()
            .unwrap_or(CapabilityReport {
                backend: SandboxBackend::Bailey,
                gaps: Vec::new(),
                notes: Vec::new(),
            });
        Box::pin(async move { Ok(report) })
    }

    fn launch(
        self: Arc<Self>,
        launch: SandboxLaunch,
    ) -> Pin<Box<dyn Future<Output = Result<RunningBox, SandboxLaunchError>> + Send>> {
        Box::pin(async move {
            let (agent, controls) = QuietAgent::new();
            self.agents.lock().unwrap().push(controls.clone());
            self.launched.lock().unwrap().push(launch.clone());
            let project_path = launch.project_path.clone();
            Ok(RunningBox {
                process: agent,
                to_host_path: Arc::new(move |path: &str| {
                    paths::host_path_under("/workspace", &project_path, path)
                }),
                stop: Arc::new(move || {
                    controls.end();
                    Box::pin(async { false }) as Pin<Box<dyn Future<Output = bool> + Send>>
                }),
            })
        })
    }

    fn list_orphans(&self) -> Pin<Box<dyn Future<Output = Vec<String>> + Send + '_>> {
        Box::pin(async { Vec::new() })
    }

    fn remove_orphans<'a>(
        &'a self,
        _names: &'a [String],
    ) -> Pin<Box<dyn Future<Output = usize> + Send + 'a>> {
        Box::pin(async { 0 })
    }
}

/// A thread factory that answers silently, recording what it made.
struct FakeThreads {
    created: Mutex<Vec<String>>,
    closed: Arc<Mutex<Vec<EndReason>>>,
    next: Mutex<u32>,
}

impl ThreadFactory for FakeThreads {
    fn create(self: Arc<Self>, _message: IncomingMessage, name: String) -> MadeThread {
        Box::pin(async move {
            self.created.lock().unwrap().push(name);
            let id = format!("thread-{}", *self.next.lock().unwrap());
            *self.next.lock().unwrap() += 1;
            Ok(CreatedThread {
                id,
                view: self.quiet_view(),
            })
        })
    }

    fn open(self: Arc<Self>, name: String, _opener: String) -> MadeThread {
        Box::pin(async move {
            self.created.lock().unwrap().push(name);
            let id = format!("thread-{}", *self.next.lock().unwrap());
            *self.next.lock().unwrap() += 1;
            Ok(CreatedThread {
                id,
                view: self.quiet_view(),
            })
        })
    }

    fn port_for(self: Arc<Self>, _thread_id: String) -> FoundView {
        Box::pin(async move {
            Some(Arc::new(QuietView {
                closed: Arc::clone(&self.closed),
            }) as Arc<dyn SessionView>)
        })
    }

    fn release(&self, _thread_id: &str) {}
}

impl FakeThreads {
    fn quiet_view(&self) -> Arc<QuietView> {
        Arc::new(QuietView {
            closed: Arc::clone(&self.closed),
        })
    }
}

/// A view that records only that its session ended.
struct QuietView {
    closed: Arc<Mutex<Vec<EndReason>>>,
}

impl SessionView for QuietView {
    fn observe<'a>(
        &'a self,
        event: &'a SessionEvent,
    ) -> Pin<Box<dyn Future<Output = Result<(), ViewError>> + Send + 'a>> {
        Box::pin(async move {
            if let SessionEvent::Close { reason } = event {
                self.closed.lock().unwrap().push(*reason);
            }
            Ok(())
        })
    }
}

fn config_with(overrides: &serde_json::Value) -> Config {
    let mut base = json!({
        "chat": {
            "token": "a.token.value",
            "channelId": "chan",
            "allowedUserIds": [OWNER],
        },
        "agent": {
            "provider": "anthropic",
            "credentialName": "ANTHROPIC_API_KEY",
            "credential": "secret",
        },
        "projectRoot": "/tmp/errand-projects",
        "stateDir": "/tmp/errand-state",
    });
    if let Some(overrides) = overrides.as_object() {
        for (key, value) in overrides {
            base[key.as_str()] = value.clone();
        }
    }
    validate_config(&base).expect("the test configuration is accepted")
}

fn raw(content: &str) -> RawMessage {
    RawMessage {
        id: "m1".to_owned(),
        author_id: OWNER.to_owned(),
        author_name: Some("amelia".to_owned()),
        author_is_bot: false,
        channel_id: "chan".to_owned(),
        parent_channel_id: None,
        content: content.to_owned(),
        attachments: Vec::new(),
    }
}

fn raw_with(content: &str, id: &str, author_id: &str) -> RawMessage {
    let mut sent = raw(content);
    sent.id = id.to_owned();
    sent.author_id = author_id.to_owned();
    sent
}

struct Harness {
    daemon: Daemon,
    threads: Arc<FakeThreads>,
    replies: Arc<Mutex<Vec<String>>>,
    lines: Arc<Mutex<Vec<(LogLevel, String)>>>,
    _root: tempfile::TempDir,
}

struct DaemonCase {
    settings: Option<serde_json::Value>,
    power_off: Option<super::PowerOff>,
    describe_usage: Option<super::DescribeUsage>,
    report: Option<CapabilityReport>,
    start: bool,
    memory: Option<Arc<MemoryStore>>,
}

impl Default for DaemonCase {
    fn default() -> Self {
        Self {
            settings: None,
            power_off: None,
            describe_usage: None,
            report: None,
            start: true,
            memory: None,
        }
    }
}

async fn with_daemon(
    case: DaemonCase,
    run: impl FnOnce(&Harness) -> Pin<Box<dyn Future<Output = ()> + '_>>,
) {
    let root = tempfile::tempdir().expect("a temp directory");
    let mut settings = json!({
        "projectRoot": root.path().join("projects").display().to_string(),
        "stateDir": root.path().join("state").display().to_string(),
    });
    if let Some(overrides) = case.settings.as_ref().and_then(|value| value.as_object()) {
        for (key, value) in overrides {
            settings[key.as_str()] = value.clone();
        }
    }
    let config = config_with(&settings);
    let threads = Arc::new(FakeThreads {
        created: Mutex::new(Vec::new()),
        closed: Arc::new(Mutex::new(Vec::new())),
        next: Mutex::new(1),
    });
    let sandbox = FakeSandbox::new(case.report.clone());
    let replies = Arc::new(Mutex::new(Vec::new()));
    let lines = Arc::new(Mutex::new(Vec::new()));

    let daemon = Daemon::new(DaemonOptions {
        config,
        sandbox: Arc::clone(&sandbox) as Arc<dyn SandboxPool>,
        threads: Arc::clone(&threads) as Arc<dyn ThreadFactory>,
        describe_images: None,
        log: {
            let lines = Arc::clone(&lines);
            Logger::new(
                LogFields::new(),
                Arc::new(move |level, line| {
                    lines.lock().unwrap().push((level, line.to_owned()));
                }),
            )
        },
        reply_in_channel: {
            let replies = Arc::clone(&replies);
            Arc::new(move |_message: IncomingMessage, text: String| {
                let replies = Arc::clone(&replies);
                Box::pin(async move { replies.lock().unwrap().push(text) })
            })
        },
        memory: case.memory.clone(),
        power_off: case.power_off.clone(),
        describe_usage: case.describe_usage.clone(),
        public_url: None,
        available_models: Vec::new(),
        delegate_base_url: None,
        operator_ids: None,
        unavailable: None,
    });

    let harness = Harness {
        daemon,
        threads,
        replies,
        lines,
        _root: root,
    };

    if case.start {
        harness.daemon.start(None).await.expect("the daemon starts");
    }

    run(&harness).await;

    harness.daemon.shutdown().await;
}

fn created(threads: &FakeThreads) -> Vec<String> {
    threads.created.lock().unwrap().clone()
}

#[tokio::test]
async fn starting_reports_the_configuration_with_no_secret_in_it() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            let logged = harness
                .lines
                .lock()
                .unwrap()
                .iter()
                .map(|(_, line)| line.clone())
                .collect::<Vec<_>>()
                .join("\n");

            assert!(harness.daemon.is_accepting());
            assert!(logged.contains("effective configuration"));
            assert!(!logged.contains("a.token.value"));
            assert!(logged.contains("[redacted]"));
        })
    })
    .await;
}

/// A crashed daemon must not leave agents running against a project.
#[tokio::test]
async fn nothing_is_acted_on_before_startup_has_finished() {
    with_daemon(
        DaemonCase {
            start: false,
            ..Default::default()
        },
        |harness| {
            Box::pin(async move {
                harness
                    .daemon
                    .handle(raw("demo: go"), InboundDecision::Start)
                    .await;

                assert!(created(&harness.threads).is_empty());
                assert_eq!(
                    harness
                        .daemon
                        .run_command(&SlashCommand {
                            thread_id: Some("thread-1".to_owned()),
                            user_id: OWNER.to_owned(),
                            user_name: "amelia".to_owned(),
                            content: "!status".to_owned(),
                        })
                        .await,
                    "the daemon is still starting up"
                );
            })
        },
    )
    .await;
}

#[tokio::test]
async fn a_message_in_the_channel_starts_a_session_in_a_thread() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("demo: fix the parser"), InboundDecision::Start)
                .await;

            assert_eq!(created(&harness.threads), ["demo: fix the parser"]);
            assert_eq!(harness.daemon.sessions().sessions().len(), 1);
        })
    })
    .await;
}

/// The channel is where people talk; an aside there is not work to start.
#[tokio::test]
async fn an_aside_in_the_channel_starts_nothing_and_says_nothing() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("!!! anyone around?"), InboundDecision::Start)
                .await;

            assert!(created(&harness.threads).is_empty());
            assert!(harness.replies.lock().unwrap().is_empty());
        })
    })
    .await;
}

/// Opening a thread and a sandbox to print a list is not an answer.
#[tokio::test]
async fn help_in_the_channel_is_answered_without_starting_anything() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("!help"), InboundDecision::Start)
                .await;

            assert!(created(&harness.threads).is_empty());
            assert!(harness.replies.lock().unwrap()[0].contains("!steer"));
        })
    })
    .await;
}

#[tokio::test]
async fn a_command_needing_a_session_is_left_alone_in_the_channel() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("!ls src"), InboundDecision::Start)
                .await;
            harness
                .daemon
                .handle(
                    raw_with("!somebodyelses thing", "m2", OWNER),
                    InboundDecision::Start,
                )
                .await;

            assert!(created(&harness.threads).is_empty());
            assert!(harness.replies.lock().unwrap().is_empty());
        })
    })
    .await;
}

#[tokio::test]
async fn a_refusal_to_start_is_said_in_the_channel_where_it_was_asked() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("demo: first"), InboundDecision::Start)
                .await;
            harness
                .daemon
                .handle(
                    raw_with("demo: second", "m2", OWNER),
                    InboundDecision::Start,
                )
                .await;

            assert!(harness.replies.lock().unwrap()[0].contains("already has a live session"));
        })
    })
    .await;
}

#[tokio::test]
async fn a_message_in_a_thread_reaches_its_session() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("demo: go"), InboundDecision::Start)
                .await;

            let mut sent = raw("carry on");
            sent.id = "m2".to_owned();
            sent.channel_id = "thread-1".to_owned();
            sent.parent_channel_id = Some("chan".to_owned());
            harness
                .daemon
                .handle(
                    sent,
                    InboundDecision::Thread {
                        thread_id: "thread-1".to_owned(),
                    },
                )
                .await;

            assert!(harness.replies.lock().unwrap().is_empty());
        })
    })
    .await;
}

/// The agent's history outlives the sandbox, so a restart does not end it.
#[tokio::test]
async fn a_message_in_a_sleeping_thread_wakes_the_session() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("demo: go"), InboundDecision::Start)
                .await;
            harness
                .daemon
                .sessions()
                .end_thread("thread-1", EndReason::Idle)
                .await;
            assert_eq!(harness.daemon.sessions().sessions().len(), 0);

            harness
                .daemon
                .handle(
                    raw_with("carry on", "m2", OWNER),
                    InboundDecision::Thread {
                        thread_id: "thread-1".to_owned(),
                    },
                )
                .await;

            assert_eq!(harness.daemon.sessions().sessions().len(), 1);
        })
    })
    .await;
}

#[tokio::test]
async fn a_message_in_a_thread_that_is_over_says_where_to_start_a_new_one() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("demo: go"), InboundDecision::Start)
                .await;
            harness
                .daemon
                .sessions()
                .end_thread("thread-1", EndReason::Stopped)
                .await;

            harness
                .daemon
                .handle(
                    raw_with("hello?", "m2", OWNER),
                    InboundDecision::Thread {
                        thread_id: "thread-1".to_owned(),
                    },
                )
                .await;

            assert!(
                harness.replies.lock().unwrap()[0]
                    .contains("post in the channel to start a new one")
            );
        })
    })
    .await;
}

#[tokio::test]
async fn a_thread_archived_from_outside_ends_its_session() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("demo: go"), InboundDecision::Start)
                .await;

            harness.daemon.thread_closed("thread-1").await;

            assert_eq!(harness.daemon.sessions().sessions().len(), 0);
        })
    })
    .await;
}

/// Whoever starts a thread owns it, and owning a thread is no reason to be
/// able to turn the computer off. The only list that counts is the daemon's
/// own.
#[tokio::test]
async fn nobody_powers_off_the_host_unless_the_daemons_own_list_says_so() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("!shutdown"), InboundDecision::Start)
                .await;

            assert!(harness.replies.lock().unwrap()[0].contains("nobody may power off this host"));
            assert!(created(&harness.threads).is_empty());
        })
    })
    .await;
}

#[tokio::test]
async fn an_account_not_on_the_shutdown_list_is_refused() {
    with_daemon(
        DaemonCase {
            settings: Some(json!({ "shutdown": { "allowedUserIds": [OWNER] } })),
            ..Default::default()
        },
        |harness| {
            Box::pin(async move {
                harness
                    .daemon
                    .handle(raw_with("!shutdown", "m1", "999"), InboundDecision::Start)
                    .await;

                assert!(harness.replies.lock().unwrap()[0].contains("not on the list"));
            })
        },
    )
    .await;
}

#[tokio::test]
async fn an_account_on_the_list_powers_the_host_off() {
    with_daemon(
        DaemonCase {
            settings: Some(json!({ "shutdown": { "allowedUserIds": [OWNER] } })),
            power_off: Some(Arc::new(|| {
                Box::pin(async { None::<String> })
                    as Pin<Box<dyn Future<Output = Option<String>> + Send>>
            })),
            ..Default::default()
        },
        |harness| {
            Box::pin(async move {
                harness
                    .daemon
                    .handle(raw("!shutdown"), InboundDecision::Start)
                    .await;

                assert!(harness.replies.lock().unwrap()[0].contains("powering off now"));
                let logged = harness
                    .lines
                    .lock()
                    .unwrap()
                    .iter()
                    .map(|(_, line)| line.clone())
                    .collect::<Vec<_>>()
                    .join("\n");
                assert!(logged.contains("powering off on request"));
            })
        },
    )
    .await;
}

#[tokio::test]
async fn a_power_off_that_fails_says_what_went_wrong() {
    with_daemon(
        DaemonCase {
            settings: Some(json!({ "shutdown": { "allowedUserIds": [OWNER] } })),
            power_off: Some(Arc::new(|| {
                Box::pin(async { Some("systemctl refused".to_owned()) })
                    as Pin<Box<dyn Future<Output = Option<String>> + Send>>
            })),
            ..Default::default()
        },
        |harness| {
            Box::pin(async move {
                harness
                    .daemon
                    .handle(raw("!shutdown"), InboundDecision::Start)
                    .await;

                assert!(harness.replies.lock().unwrap()[0].contains("systemctl refused"));
            })
        },
    )
    .await;
}

/// Shutting down from inside a thread must not be a way around the list.
#[tokio::test]
async fn the_shutdown_list_governs_the_slash_command_too() {
    with_daemon(
        DaemonCase {
            settings: Some(json!({ "shutdown": { "allowedUserIds": [OWNER] } })),
            ..Default::default()
        },
        |harness| {
            Box::pin(async move {
                let answer = harness
                    .daemon
                    .run_command(&SlashCommand {
                        thread_id: Some("thread-1".to_owned()),
                        user_id: "999".to_owned(),
                        user_name: "somebody".to_owned(),
                        content: "!shutdown".to_owned(),
                    })
                    .await;

                assert!(answer.contains("not on the list"));
            })
        },
    )
    .await;
}

#[tokio::test]
async fn a_slash_command_runs_the_same_command_a_message_would() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("demo: go"), InboundDecision::Start)
                .await;

            let answer = harness
                .daemon
                .run_command(&SlashCommand {
                    thread_id: Some("thread-1".to_owned()),
                    user_id: OWNER.to_owned(),
                    user_name: "amelia".to_owned(),
                    content: "!status".to_owned(),
                })
                .await;

            assert_eq!(answer, "ran !status");
        })
    })
    .await;
}

/// A help listing wants to go back to whoever asked, not into the channel.
#[tokio::test]
async fn a_slash_command_that_needs_no_session_answers_the_caller_directly() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            let answer = harness
                .daemon
                .run_command(&SlashCommand {
                    thread_id: None,
                    user_id: OWNER.to_owned(),
                    user_name: "amelia".to_owned(),
                    content: "!help".to_owned(),
                })
                .await;

            assert!(answer.contains("!steer"));
            assert!(harness.replies.lock().unwrap().is_empty());
        })
    })
    .await;
}

#[tokio::test]
async fn a_slash_command_outside_a_thread_says_where_to_use_it() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            let answer = harness
                .daemon
                .run_command(&SlashCommand {
                    thread_id: None,
                    user_id: OWNER.to_owned(),
                    user_name: "amelia".to_owned(),
                    content: "!ls".to_owned(),
                })
                .await;

            assert!(answer.contains("post in the channel to start one"));
        })
    })
    .await;
}

#[tokio::test]
async fn a_slash_command_in_a_sleeping_thread_says_to_wake_it_first() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("demo: go"), InboundDecision::Start)
                .await;
            harness
                .daemon
                .sessions()
                .end_thread("thread-1", EndReason::Idle)
                .await;

            let answer = harness
                .daemon
                .run_command(&SlashCommand {
                    thread_id: Some("thread-1".to_owned()),
                    user_id: OWNER.to_owned(),
                    user_name: "amelia".to_owned(),
                    content: "!ls".to_owned(),
                })
                .await;

            assert!(answer.contains("post a message in it to wake the session"));
        })
    })
    .await;
}

#[tokio::test]
async fn shutting_down_ends_every_session_and_stops_accepting() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("demo: go"), InboundDecision::Start)
                .await;

            harness.daemon.shutdown().await;

            assert!(!harness.daemon.is_accepting());
            assert!(harness.daemon.sessions().sessions().is_empty());
            assert_eq!(
                *harness.threads.closed.lock().unwrap(),
                [EndReason::Shutdown]
            );
        })
    })
    .await;
}

/// Presenting a weaker boundary as a stronger one is worse than the weaker
/// boundary, because it removes the chance to decide about it.
#[test]
fn the_startup_report_always_states_what_cannot_be_enforced() {
    let lines = render_startup_report(
        &CapabilityReport {
            backend: SandboxBackend::Bailey,
            gaps: ["seccomp is unavailable".to_owned()].into_iter().collect(),
            notes: ["landlock v5".to_owned()].into_iter().collect(),
        },
        &[],
        None,
    )
    .join("\n");

    assert!(lines.contains("sandbox backend: bailey"));
    assert!(lines.contains("landlock v5"));
    assert!(lines.contains("1 guarantee(s) cannot be enforced"));
    assert!(lines.contains("seccomp is unavailable"));
}

#[test]
fn a_backend_with_nothing_missing_says_so_plainly() {
    let lines = render_startup_report(
        &CapabilityReport {
            backend: SandboxBackend::Podman,
            gaps: Vec::new(),
            notes: Vec::new(),
        },
        &[],
        None,
    )
    .join("\n");

    assert!(lines.contains("enforces every configured guarantee"));
}

/// Anyone who can post can run code, which is worth saying out loud.
#[test]
fn an_open_allowlist_is_reported_as_the_decision_it_is() {
    let config = config_with(&json!({
        "chat": {
            "token": "t",
            "channelId": "c",
            "allowedUserIds": ["*"],
            "blockedUserIds": ["9"],
        },
    }));
    let lines = render_startup_report(
        &CapabilityReport {
            backend: SandboxBackend::Bailey,
            gaps: Vec::new(),
            notes: Vec::new(),
        },
        &[],
        Some(&config.chat),
    )
    .join("\n");

    assert!(lines.contains("open to everyone who can post"));
    assert!(lines.contains("1 blocked"));
}

#[test]
fn a_setting_the_chosen_backend_ignores_is_reported_as_inert() {
    assert!(inert_settings(&config_with(&json!({}))).is_empty());
    assert_eq!(
        inert_settings(&config_with(&json!({
            "sandbox": { "image": "localhost/mine:v2" },
        }))),
        ["sandbox.image is set but only the podman backend uses it".to_owned()]
    );
    assert!(
        inert_settings(&config_with(&json!({
            "sandbox": { "backend": "podman", "image": "localhost/mine:v2" },
        })))
        .is_empty()
    );
}

/// A guarantee that cannot be met must not be started around silently.
#[tokio::test]
async fn a_gap_the_configuration_forbids_stops_the_daemon_starting() {
    with_daemon(
        DaemonCase {
            start: false,
            report: Some(CapabilityReport {
                backend: SandboxBackend::Bailey,
                gaps: ["no landlock here".to_owned()].into_iter().collect(),
                notes: Vec::new(),
            }),
            ..Default::default()
        },
        |harness| {
            Box::pin(async move {
                assert!(matches!(
                    harness.daemon.start(None).await,
                    Err(StartError::EnforcementGap(_))
                ));
            })
        },
    )
    .await;
}

#[tokio::test]
async fn the_same_gap_is_allowed_when_the_configuration_allows_it() {
    with_daemon(
        DaemonCase {
            start: false,
            settings: Some(json!({ "sandbox": { "requireFullEnforcement": false } })),
            report: Some(CapabilityReport {
                backend: SandboxBackend::Bailey,
                gaps: ["no landlock here".to_owned()].into_iter().collect(),
                notes: Vec::new(),
            }),
            ..Default::default()
        },
        |harness| {
            Box::pin(async move {
                harness
                    .daemon
                    .start(None)
                    .await
                    .expect("the gap is allowed");

                assert!(harness.daemon.is_accepting());
                let logged = harness
                    .lines
                    .lock()
                    .unwrap()
                    .iter()
                    .map(|(_, line)| line.clone())
                    .collect::<Vec<_>>()
                    .join("\n");
                assert!(logged.contains("no landlock here"));
            })
        },
    )
    .await;
}

/// About the account the host shares, so a session is not needed to ask.
#[tokio::test]
async fn the_usage_window_is_reported_wherever_it_is_asked_about() {
    with_daemon(
        DaemonCase {
            describe_usage: Some(Arc::new(|| {
                Box::pin(async {
                    "58% of the provider's usage window is left, and it resets in 2 hours"
                        .to_owned()
                })
            })),
            ..Default::default()
        },
        |harness| {
            Box::pin(async move {
                harness
                    .daemon
                    .handle(raw("!usage"), InboundDecision::Start)
                    .await;

                assert!(
                    harness.replies.lock().unwrap()[0]
                        .contains("58% of the provider's usage window is left")
                );
                assert!(created(&harness.threads).is_empty());
                assert_eq!(
                    harness
                        .daemon
                        .run_command(&SlashCommand {
                            thread_id: None,
                            user_id: OWNER.to_owned(),
                            user_name: "amelia".to_owned(),
                            content: "!usage".to_owned(),
                        })
                        .await,
                    harness.replies.lock().unwrap()[0].clone()
                );
            })
        },
    )
    .await;
}

#[tokio::test]
async fn a_provider_that_meters_nothing_says_so_rather_than_inventing_a_number() {
    with_daemon(DaemonCase::default(), |harness| {
        Box::pin(async move {
            harness
                .daemon
                .handle(raw("!usage"), InboundDecision::Start)
                .await;

            assert!(harness.replies.lock().unwrap()[0].contains("does not report a usage window"));
        })
    })
    .await;
}

/// Memory is about a person, not a session, so asking should not need a
/// thread.
#[tokio::test]
async fn facts_is_answered_in_the_channel_with_no_session_running() {
    let memory = Arc::new(MemoryStore::open(":memory:").expect("the store opens"));
    memory
        .remember(Scope::User, OWNER, "prefers jj over git", "earlier", 0)
        .unwrap();

    with_daemon(
        DaemonCase {
            memory: Some(Arc::clone(&memory)),
            ..Default::default()
        },
        |harness| {
            Box::pin(async move {
                harness
                    .daemon
                    .handle(raw("!facts"), InboundDecision::Start)
                    .await;

                assert!(
                    harness
                        .replies
                        .lock()
                        .unwrap()
                        .join("\n")
                        .contains("prefers jj over git")
                );
                // Answered outright: no thread was opened and no session
                // started.
                assert!(created(&harness.threads).is_empty());
            })
        },
    )
    .await;
}

#[tokio::test]
async fn a_project_is_a_threads_own_so_the_channel_says_to_ask_there() {
    let memory = Arc::new(MemoryStore::open(":memory:").expect("the store opens"));
    with_daemon(
        DaemonCase {
            memory: Some(Arc::clone(&memory)),
            ..Default::default()
        },
        |harness| {
            Box::pin(async move {
                harness
                    .daemon
                    .handle(raw("!facts project"), InboundDecision::Start)
                    .await;
                assert!(
                    harness
                        .replies
                        .lock()
                        .unwrap()
                        .join("\n")
                        .contains("ask in one")
                );
            })
        },
    )
    .await;
}

/// Owner means nothing in a channel, so forgetting there is the operator's.
#[tokio::test]
async fn forget_in_the_channel_is_refused_to_anyone_but_an_operator() {
    let memory = Arc::new(MemoryStore::open(":memory:").expect("the store opens"));
    memory
        .remember(Scope::User, OWNER, "prefers jj over git", "earlier", 0)
        .unwrap();

    with_daemon(
        DaemonCase {
            memory: Some(Arc::clone(&memory)),
            ..Default::default()
        },
        |harness| {
            Box::pin(async move {
                harness
                    .daemon
                    .handle(raw(&format!("!forget <@{OWNER}>")), InboundDecision::Start)
                    .await;

                assert!(
                    harness
                        .replies
                        .lock()
                        .unwrap()
                        .join("\n")
                        .contains("only an operator")
                );
                assert_eq!(memory.facts_for(Scope::User, OWNER, 100).unwrap().len(), 1);
            })
        },
    )
    .await;
}

/// Inside a thread the session answers, because it knows the project.
#[tokio::test]
async fn in_a_thread_the_daemon_leaves_memory_to_the_session() {
    let memory = Arc::new(MemoryStore::open(":memory:").expect("the store opens"));
    memory
        .remember(Scope::User, OWNER, "prefers jj over git", "earlier", 0)
        .unwrap();

    with_daemon(
        DaemonCase {
            memory: Some(Arc::clone(&memory)),
            ..Default::default()
        },
        |harness| {
            Box::pin(async move {
                harness
                    .daemon
                    .handle(
                        raw("!facts"),
                        InboundDecision::Thread {
                            thread_id: "t1".to_owned(),
                        },
                    )
                    .await;
                // Not answered here, so it falls through to whatever the
                // thread holds.
                assert!(
                    !harness
                        .replies
                        .lock()
                        .unwrap()
                        .join("\n")
                        .contains("prefers jj over git")
                );
            })
        },
    )
    .await;
}

#[tokio::test]
async fn an_operator_may_forget_from_the_channel_and_is_told_what_went() {
    let memory = Arc::new(MemoryStore::open(":memory:").expect("the store opens"));
    memory
        .remember(Scope::User, OWNER, "prefers jj over git", "earlier", 0)
        .unwrap();

    with_daemon(
        DaemonCase {
            memory: Some(Arc::clone(&memory)),
            settings: Some(json!({
                "chat": {
                    "token": "t",
                    "channelId": "chan",
                    "allowedUserIds": [OWNER],
                    "operatorUserIds": [OWNER],
                },
            })),
            ..Default::default()
        },
        |harness| {
            Box::pin(async move {
                harness
                    .daemon
                    .handle(raw(&format!("!forget <@{OWNER}>")), InboundDecision::Start)
                    .await;

                assert!(
                    harness
                        .replies
                        .lock()
                        .unwrap()
                        .join("\n")
                        .contains("forgot 1 fact about")
                );
                assert_eq!(memory.facts_for(Scope::User, OWNER, 100).unwrap().len(), 0);
            })
        },
    )
    .await;
}

/// The builder names the backend configuration asked for, never a fallback.
#[test]
fn create_sandbox_names_the_configured_backend() {
    let root = tempfile::tempdir().unwrap();
    let config = config_with(&json!({
        "projectRoot": root.path().join("projects").display().to_string(),
        "stateDir": root.path().join("state").display().to_string(),
    }));
    let sandbox = create_sandbox(&config, silent(), None, None);
    assert!(matches!(sandbox, Backend::Bailey(_)));

    let config = config_with(&json!({
        "projectRoot": root.path().join("projects").display().to_string(),
        "stateDir": root.path().join("state").display().to_string(),
        "sandbox": { "backend": "podman" },
    }));
    let sandbox = create_sandbox(&config, silent(), None, None);
    assert!(matches!(sandbox, Backend::Podman(_)));
}