synaps-engine 0.11.1

Runtime engine — streaming, tools, MCP, skills, extensions, sidecar
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
use super::{strip_ansi, Tool, ToolContext};
use crate::{Result, RuntimeError};
use serde_json::{json, Value};
use zeroize::Zeroizing;

const BASH_INTERMEDIARY_CHANNEL_CAPACITY: usize = 64;
static BASH_INTERMEDIARY_PRODUCED_BYTES: std::sync::atomic::AtomicU64 =
    std::sync::atomic::AtomicU64::new(0);
static BASH_INTERMEDIARY_ACCEPTED_BYTES: std::sync::atomic::AtomicU64 =
    std::sync::atomic::AtomicU64::new(0);
static BASH_INTERMEDIARY_CONSUMED_BYTES: std::sync::atomic::AtomicU64 =
    std::sync::atomic::AtomicU64::new(0);
static BASH_INTERMEDIARY_DROPPED_BYTES: std::sync::atomic::AtomicU64 =
    std::sync::atomic::AtomicU64::new(0);

#[derive(Debug, Clone, Copy)]
pub struct BashIntermediarySnapshot {
    pub produced_bytes: u64,
    pub accepted_bytes: u64,
    pub consumed_bytes: u64,
    pub dropped_bytes: u64,
    pub retained_bytes: u64,
}

impl BashIntermediarySnapshot {
    /// Every byte ever produced has been consumed or dropped: nothing is in
    /// flight anywhere in the process. A leaked byte keeps this false forever.
    pub fn is_settled(&self) -> bool {
        self.produced_bytes == self.consumed_bytes + self.dropped_bytes
    }
}

/// Counters are read downstream-first. Each one only grows, and upstream
/// counts are bumped before the bytes move on, so a snapshot torn by a
/// concurrent relay can overstate in-flight bytes but never understate them:
/// `is_settled` is never true unless the process really was settled.
pub fn bash_intermediary_snapshot() -> BashIntermediarySnapshot {
    use std::sync::atomic::Ordering::SeqCst;
    let consumed = BASH_INTERMEDIARY_CONSUMED_BYTES.load(SeqCst);
    let dropped = BASH_INTERMEDIARY_DROPPED_BYTES.load(SeqCst);
    let accepted = BASH_INTERMEDIARY_ACCEPTED_BYTES.load(SeqCst);
    let produced = BASH_INTERMEDIARY_PRODUCED_BYTES.load(SeqCst);
    BashIntermediarySnapshot {
        produced_bytes: produced,
        accepted_bytes: accepted,
        consumed_bytes: consumed,
        dropped_bytes: dropped,
        retained_bytes: produced.saturating_sub(consumed).saturating_sub(dropped),
    }
}

/// Test oracle for the handoff counters: wait until the whole process is
/// settled. Concurrent relays only delay it; a leaked byte times it out.
#[cfg(test)]
async fn wait_handoff_settled() -> BashIntermediarySnapshot {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
    loop {
        let now = bash_intermediary_snapshot();
        if now.is_settled() {
            return now;
        }
        assert!(std::time::Instant::now() < deadline, "handoff bytes never settled: {now:?}");
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
    }
}

pub struct BashTool;

/// One sanitized read in flight between a stream reader and the executor.
/// Its bytes are counted out exactly once: `consume` when the executor takes
/// it, or `Drop` when it never arrives (the channel closed before the send,
/// or it was still queued when the receiver went away on timeout or cancel).
/// Tokio drops queued values with the channel, so no path can leak a count.
struct HandoffChunk(Option<String>);

impl HandoffChunk {
    fn new(text: String) -> Self {
        BASH_INTERMEDIARY_PRODUCED_BYTES
            .fetch_add(text.len() as u64, std::sync::atomic::Ordering::SeqCst);
        Self(Some(text))
    }

    fn len(&self) -> usize {
        self.0.as_ref().map_or(0, String::len)
    }

    fn consume(mut self) -> String {
        let text = self.0.take().unwrap_or_default();
        BASH_INTERMEDIARY_CONSUMED_BYTES
            .fetch_add(text.len() as u64, std::sync::atomic::Ordering::SeqCst);
        text
    }
}

impl Drop for HandoffChunk {
    fn drop(&mut self) {
        if let Some(text) = self.0.take() {
            BASH_INTERMEDIARY_DROPPED_BYTES
                .fetch_add(text.len() as u64, std::sync::atomic::Ordering::SeqCst);
        }
    }
}

const READ_CHUNK_SIZE: usize = 1024;
const MAX_STREAMED_DELTA_BYTES: usize = 16 * 1024;

/// sudo passwords handed out during one command, redacted from its output
/// and zeroized when dropped.
pub(crate) type Redactions = std::sync::Arc<std::sync::Mutex<Vec<Zeroizing<String>>>>;

/// The askpass broker one bash call uses (Linux), prepared before spawn.
#[cfg(target_os = "linux")]
pub(crate) type Askpass = super::sudo_askpass::broker::PreparedBroker;
#[cfg(not(target_os = "linux"))]
pub(crate) type Askpass = std::convert::Infallible;

fn sanitize_output(input: &str) -> String {
    let stripped = strip_ansi(input);
    stripped
        .chars()
        .filter(|ch| {
            *ch == '\n' || *ch == '\r' || *ch == '\t' || (!ch.is_control() && *ch != '\u{7f}')
        })
        .collect()
}

/// Read one child stream in `READ_CHUNK_SIZE` chunks and forward the
/// sanitized text to the bash executor, tagged stdout/stderr. A character
/// split between two reads is held back and decoded whole (#286); only an
/// incomplete sequence (at most 3 bytes) waits, so prompts without a
/// trailing newline are still forwarded as soon as they are read.
async fn forward_output<R>(
    mut reader: R,
    is_stderr: bool,
    tx: tokio::sync::mpsc::Sender<(bool, HandoffChunk)>,
) where
    R: tokio::io::AsyncRead + Unpin,
{
    use tokio::io::AsyncReadExt;
    let mut buf = vec![0u8; READ_CHUNK_SIZE];
    let mut decoder = super::utf8_stream::Utf8StreamDecoder::new();
    loop {
        let (text, eof) = match reader.read(&mut buf).await {
            Ok(0) | Err(_) => (decoder.finish(), true),
            Ok(n) => (decoder.decode(&buf[..n]), false),
        };
        let msg = sanitize_output(&text);
        if !msg.is_empty() {
            let chunk = HandoffChunk::new(msg);
            // Count acceptance before the send makes the chunk visible, so
            // accepted >= consumed holds at every instant. A closed channel
            // drops the chunk here, and its Drop counts it.
            let Ok(permit) = tx.reserve().await else {
                break;
            };
            BASH_INTERMEDIARY_ACCEPTED_BYTES
                .fetch_add(chunk.len() as u64, std::sync::atomic::Ordering::SeqCst);
            permit.send((is_stderr, chunk));
        }
        if eof {
            break;
        }
    }
}

fn append_bounded(output: &mut String, text: &str, max_output: usize) -> bool {
    if output.len() >= max_output {
        return false;
    }
    let remaining = max_output - output.len();
    if text.len() <= remaining {
        output.push_str(text);
        true
    } else {
        let mut end = remaining;
        while end > 0 && !text.is_char_boundary(end) {
            end -= 1;
        }
        output.push_str(&text[..end]);
        false
    }
}

/// Resolve the bash executable for the bash tool.
///
/// Unix: `bash` from PATH, as always. Windows: bash is usually NOT on PATH —
/// prefer an explicit PATH hit, then Git Bash's known install locations, then
/// WSL's `bash.exe` (runs inside the default distro) as a last resort.
pub(crate) fn bash_program() -> std::ffi::OsString {
    #[cfg(unix)]
    {
        "bash".into()
    }
    #[cfg(windows)]
    {
        let on_path = std::env::var_os("PATH")
            .map(|p| std::env::split_paths(&p).any(|d| d.join("bash.exe").is_file()))
            .unwrap_or(false);
        if on_path {
            return "bash".into();
        }
        for var in ["ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"] {
            if let Some(pf) = std::env::var_os(var) {
                let candidate = std::path::Path::new(&pf).join(r"Git\bin\bash.exe");
                if candidate.is_file() {
                    return candidate.into_os_string();
                }
            }
        }
        let wsl = std::path::Path::new(r"C:\Windows\System32\bash.exe");
        if wsl.is_file() {
            return wsl.as_os_str().to_os_string();
        }
        // Nothing found — let spawn fail with a readable NotFound error.
        "bash".into()
    }
}

/// The command, behind a `sudo` shell function. The child has no terminal
/// (setsid), so a bare sudo could not prompt anyway. With the askpass
/// broker (Linux, see `sudo_askpass`) sudo asks the user through the
/// verified helper; without it (other platforms, embedders, setup failure)
/// sudo must not ask at all: `-n` fails with sudo's own "a password is
/// required", and NOPASSWD rules work either way. The password never
/// travels through the command's stdin, which is empty.
pub(crate) fn bash_script_with_secure_sudo(command: &str, askpass: bool) -> String {
    #[cfg(unix)]
    let call = if askpass {
        r#"command sudo -A "$@""#
    } else {
        r#"command sudo -n "$@""#
    };
    #[cfg(not(unix))]
    let call = {
        let _ = askpass;
        r#"command sudo -S -p '[sudo] password required: ' "$@""#
    };
    format!(
        r#"sudo() {{
    {call}
}}
{command}"#
    )
}

/// Resolve the PowerShell executable. Prefers pwsh (PowerShell 7+, the
/// cross-platform build with sane defaults) and falls back to the
/// Windows-bundled powershell.exe (5.1).
#[cfg(windows)]
pub(crate) fn powershell_program() -> std::ffi::OsString {
    let on_path = |exe: &str| {
        std::env::var_os("PATH")
            .map(|p| std::env::split_paths(&p).any(|d| d.join(exe).is_file()))
            .unwrap_or(false)
    };
    if on_path("pwsh.exe") {
        return "pwsh".into();
    }
    for var in ["ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"] {
        if let Some(pf) = std::env::var_os(var) {
            let candidate = std::path::Path::new(&pf).join(r"PowerShell\7\pwsh.exe");
            if candidate.is_file() {
                return candidate.into_os_string();
            }
        }
    }
    // powershell.exe is always present on Windows (System32).
    "powershell".into()
}

/// Unix stub — the powershell tool is only registered on Windows, so this is
/// never called there; it exists so cross-compilation `cargo check` works.
#[cfg(not(windows))]
pub(crate) fn powershell_program() -> std::ffi::OsString {
    "pwsh".into()
}

#[async_trait::async_trait]
impl Tool for BashTool {
    fn origin(&self) -> crate::tools::ToolOrigin {
        crate::tools::ToolOrigin::Builtin
    }

    /// Explicitly NonIdempotent (Task 24): arbitrary shell side effects —
    /// serialized execution, no concurrency key.
    fn effect(&self) -> crate::tools::catalog::ToolEffect {
        crate::tools::catalog::ToolEffect::NonIdempotent
    }

    fn name(&self) -> &str {
        "bash"
    }

    fn description(&self) -> &str {
        "Execute a bash command and return its output. Use for running programs, installing packages, git operations, and any shell commands. Commands time out after 30 seconds by default; pass a larger timeout when needed. Stdin is empty. On Linux, if sudo needs a password, the user is asked in the TUI, shown the command sudo will run, and the password goes only to sudo, never to the model. Other password prompts are not answered."
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "The bash command to execute"
                },
                "timeout": {
                    "type": "integer",
                    "description": "Timeout in seconds (default: 30). Use a larger value for long-running commands."
                }
            },
            "required": ["command"]
        })
    }

    async fn execute(&self, params: Value, ctx: ToolContext) -> Result<String> {
        let command = params["command"]
            .as_str()
            .ok_or_else(|| RuntimeError::Tool("Missing command parameter".to_string()))?;

        run_bash(command, params["timeout"].as_u64(), ctx, prepare_askpass()).await
    }
}

/// The production askpass broker, if this platform and binary support it.
fn prepare_askpass() -> Option<Askpass> {
    #[cfg(target_os = "linux")]
    {
        use super::sudo_askpass::broker::{AskpassConfig, PreparedBroker};
        let config = AskpassConfig::production()?;
        match PreparedBroker::prepare(&config) {
            Ok(broker) => Some(broker),
            Err(e) => {
                tracing::warn!("sudo askpass unavailable for this command: {e}");
                None
            }
        }
    }
    #[cfg(not(target_os = "linux"))]
    {
        None
    }
}

pub(crate) async fn run_bash(
    command: &str,
    timeout: Option<u64>,
    ctx: ToolContext,
    askpass: Option<Askpass>,
) -> Result<String> {
    let script = bash_script_with_secure_sudo(command, askpass.is_some());
    run_shell_command(&script, ShellSpec::Bash, timeout, ctx, askpass).await
}

/// Kills the command's whole process group unless the command finished on
/// its own. `child.kill()` stops only the shell: everything the command
/// started (a test runner's workers, `cmd &` jobs) used to keep running, and
/// keep using memory, after a timeout or cancel (S348). The command leads its
/// own group: `setsid` in `pre_exec`, and `systemd-run --scope` execs in
/// place, so the pid is the group id. Dropped before the `Child`, so the
/// leader is not reaped by Child drop before the kill. Explicit kill paths
/// signal/disarm first; normal wait disarms synchronously on completion.
struct KillGroupUnlessFinished {
    pgid: Option<u32>,
}

impl KillGroupUnlessFinished {
    fn new(pid: Option<u32>) -> Self {
        Self { pgid: pid }
    }

    /// The command exited by itself: nothing to kill.
    fn finished(&mut self) {
        self.pgid = None;
    }

    /// Signal and disarm BEFORE any explicit kill/wait can reap the leader.
    fn kill_now(&mut self) {
        #[cfg(unix)]
        if let Some(pgid) = self.pgid.take() {
            // SAFETY: killpg(2) on our own child's process group.
            unsafe {
                libc::killpg(pgid as libc::pid_t, libc::SIGKILL);
            }
        }
        #[cfg(not(unix))]
        {
            self.pgid = None;
        }
    }
}

impl Drop for KillGroupUnlessFinished {
    fn drop(&mut self) {
        self.kill_now();
    }
}

/// Which shell backend the shared executor drives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ShellSpec {
    Bash,
    PowerShell,
}

impl ShellSpec {
    /// Names the command's systemd scope (`systemctl --user list-units --type=scope`).
    fn scope_description(self) -> &'static str {
        match self {
            ShellSpec::Bash => "synaps tool: bash",
            ShellSpec::PowerShell => "synaps tool: powershell",
        }
    }
}

/// Shared execution core for bash + powershell: empty stdin, piped
/// stdout/stderr, chunked streaming with byte-conservation accounting, the
/// sudo askpass broker (bash on Linux), truncation, timeout. The only
/// per-shell differences are which program is spawned and which args it
/// takes. Nothing the command prints can raise a password prompt: only a
/// verified sudo can, through `askpass`.
pub(crate) async fn run_shell_command(
    script: &str,
    spec: ShellSpec,
    requested_timeout: Option<u64>,
    ctx: ToolContext,
    askpass: Option<Askpass>,
) -> Result<String> {
    {
        let requested_timeout = requested_timeout.unwrap_or(ctx.limits.bash_timeout);
        // H5: enforce bash_max_timeout cap — prevent DoS via prompt injection
        // requesting unbounded timeouts (e.g. timeout:2592000 + infinite loop).
        let timeout_secs = if ctx.limits.bash_max_timeout > 0 {
            requested_timeout.min(ctx.limits.bash_max_timeout)
        } else {
            requested_timeout
        };
        let max_output = ctx.limits.max_tool_buffer;

        let (program, args): (std::ffi::OsString, Vec<std::ffi::OsString>) = match spec {
            ShellSpec::Bash => (bash_program(), vec!["-c".into(), script.into()]),
            ShellSpec::PowerShell => (
                powershell_program(),
                vec!["-NoProfile".into(), "-Command".into(), script.into()],
            ),
        };
        let effective_env = ctx.capabilities.env.as_ref()
            .map(|env| env.iter().map(|(k, v)| (k.into(), v.into())).collect())
            .unwrap_or_else(crate::process_scope::inherited_env);
        let probe_env = effective_env.clone();
        let probe_cwd = ctx.capabilities.cwd.clone();
        // This worker can only launch a bounded throwaway probe. Abandoning
        // this future can never launch the real command from the worker.
        if ctx.capabilities.launch_cancel.as_ref().is_some_and(|c| c.is_cancelled()) {
            return Err(RuntimeError::Tool("Command canceled before launch".into()));
        }
        let probe_task = tokio::task::spawn_blocking(move || {
            crate::process_scope::launcher_for_effective_env(
                &probe_env, probe_cwd.as_deref(), crate::process_scope::ScopeKind::Tool)
        });
        let launcher = if let Some(cancel) = &ctx.capabilities.launch_cancel {
            tokio::select! {
                biased;
                _ = cancel.cancelled() => return Err(RuntimeError::Tool("Command canceled before launch".into())),
                result = probe_task => result,
            }
        } else {
            probe_task.await
        }.map_err(|e| RuntimeError::Tool(e.to_string()))?;
        let (program, args) = match launcher {
            Some(launcher) => launcher.wrap(spec.scope_description(),
                crate::process_scope::resolve_program(program, &effective_env,
                    ctx.capabilities.cwd.as_deref()).map_err(|e| RuntimeError::Tool(e.to_string()))?, args),
            None => (program, args),
        };
        let mut cmd = tokio::process::Command::new(program);
        if let Some(cwd) = ctx.capabilities.cwd.as_deref() {
            cmd.current_dir(cwd);
        }
        cmd.env_clear().envs(effective_env);
        #[cfg(target_os = "linux")]
        if let Some(broker) = &askpass {
            cmd.env("SUDO_ASKPASS", broker.helper_path());
        }
        cmd.args(&args)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .kill_on_drop(true);

        // Start the child in a new session (setsid) so it has no controlling
        // terminal. Programs that open /dev/tty directly (SSH fingerprint
        // prompts, gpg pinentry, git credential helpers, pagers) will get
        // ENXIO and fail with a readable error on stderr instead of hanging
        // invisibly until timeout. Sudo asks through its askpass helper
        // instead (see bash_script_with_secure_sudo()).
        #[cfg(unix)]
        unsafe {
            cmd.pre_exec(|| {
                libc::setsid();
                Ok(())
            });
        }

        if ctx.capabilities.launch_cancel.as_ref().is_some_and(|c| c.is_cancelled()) {
            return Err(RuntimeError::Tool("Command canceled before launch".into()));
        }
        let mut child = cmd.spawn().map_err(|e| RuntimeError::Tool(e.to_string()))?;
        // Armed until the command finishes on its own: a timeout, a cancel,
        // the output cap or an abandoned password prompt kills the whole
        // process group, not just the shell.
        let mut group = KillGroupUnlessFinished::new(child.id());

        let stdout = child
            .stdout
            .take()
            .ok_or_else(|| RuntimeError::Tool("Failed to capture stdout".to_string()))?;
        let stderr = child
            .stderr
            .take()
            .ok_or_else(|| RuntimeError::Tool("Failed to capture stderr".to_string()))?;
        // Serve sudo's password requests for as long as the command runs.
        let redactions = Redactions::default();
        let password_cancel = crate::CancellationToken::new();
        #[cfg(target_os = "linux")]
        let _askpass = askpass.and_then(|broker| {
            broker
                .start(
                    child.id(),
                    ctx.capabilities.secret_prompt.clone(),
                    redactions.clone(),
                    password_cancel.clone(),
                )
                .map_err(|e| tracing::warn!("sudo askpass unavailable for this command: {e}"))
                .ok()
        });
        #[cfg(not(target_os = "linux"))]
        let _ = askpass;

        let (tx_inter, mut rx_inter) =
            tokio::sync::mpsc::channel::<(bool, HandoffChunk)>(BASH_INTERMEDIARY_CHANNEL_CAPACITY);

        tokio::spawn(forward_output(stdout, false, tx_inter.clone()));
        tokio::spawn(forward_output(stderr, true, tx_inter.clone()));

        drop(tx_inter);

        let result = tokio::time::timeout(tokio::time::Duration::from_secs(timeout_secs), async {
            let mut full_output = String::new();
            let mut truncated = false;
            let mut streamed_bytes = 0usize;

            loop {
                let item = tokio::select! {
                    biased;
                    // The user cancelled sudo's password prompt: stop the
                    // command rather than let it run on without it.
                    _ = password_cancel.cancelled() => {
                        group.kill_now();
                        let _ = child.kill().await;
                        return Err(RuntimeError::Tool(
                            "Command canceled while waiting for password".to_string(),
                        ));
                    }
                    item = rx_inter.recv() => item,
                };
                let Some((_is_stderr, chunk)) = item else {
                    break;
                };
                let mut msg = chunk.consume();
                for secret in redactions.lock().unwrap_or_else(|p| p.into_inner()).iter() {
                    if !secret.is_empty() {
                        msg = msg.replace(secret.as_str(), "[redacted]");
                    }
                }

                if truncated {
                    continue;
                }

                let added_all = append_bounded(&mut full_output, &msg, max_output);
                if let Some(ref txd) = ctx.channels.tx_delta {
                    if streamed_bytes < MAX_STREAMED_DELTA_BYTES {
                        let remaining = MAX_STREAMED_DELTA_BYTES - streamed_bytes;
                        let delta = if msg.len() <= remaining {
                            msg.clone()
                        } else {
                            crate::truncate_str(&msg, remaining).to_string()
                        };
                        streamed_bytes += delta.len();
                        if !delta.is_empty() {
                            txd.send(delta);
                        }
                    }
                }

                if !added_all {
                    full_output.push_str(&format!("\n\n[output truncated at {}]", max_output));
                    if let Some(ref txd) = ctx.channels.tx_delta {
                        txd.send(format!("\n\n[output truncated at {}]", max_output));
                    }
                    truncated = true;
                    group.kill_now();
                    let _ = child.kill().await;
                }
            }
            let status = child.wait().await;
            // wait errors may mean the leader was already reaped externally;
            // never signal a potentially recycled process-group ID afterwards.
            group.finished();
            let status = status.map_err(|e| RuntimeError::Tool(e.to_string()))?;
            // Finished on its own: leave anything it deliberately started in
            // the background (`server &`) running, as before.
            // Drop (and so zeroize) the passwords now the command is done.
            redactions.lock().unwrap_or_else(|p| p.into_inner()).clear();
            Ok::<_, RuntimeError>((status, full_output, truncated))
        })
        .await;

        match result {
            Ok(Ok((status, output, was_truncated))) => {
                if status.success() || was_truncated {
                    Ok(output)
                } else {
                    let mut notice = String::new();
                    // T5: when a command fails and references a stripped secret,
                    // append a notice (once per name per session).
                    if !ctx.capabilities.env_stripped.is_empty() {
                        let mut warned = ctx.capabilities.env_warned.lock().unwrap_or_else(|p| p.into_inner());
                        for name in &ctx.capabilities.env_stripped {
                            if warned.contains(name) {
                                continue;
                            }
                            // Word-boundary match: covers $NAME, ${NAME},
                            // ${NAME:?}, ${NAME:-x}, $env:NAME and NAME=…
                            if references_env_name(script, name) {
                                notice.push_str(&format!(
                                    "\nnote: ${name} was stripped from the session env as a secret; \
                                     reattach from a shell that has it \
                                     (synaps --system … from that shell) \
                                     — the daemon never receives credentials."
                                ));
                                warned.insert(name.clone());
                            }
                        }
                    }
                    Err(RuntimeError::Tool(format!(
                        "Command failed (exit {}):\n{}{notice}",
                        status.code().unwrap_or(-1),
                        output
                    )))
                }
            }
            Ok(Err(e)) => Err(RuntimeError::Tool(format!(
                "Failed to execute command: {}",
                e
            ))),
            Err(_) => Err(RuntimeError::Tool(format!(
                "Command timed out after {}s",
                timeout_secs
            ))),
        }
    }
}

/// Does `script` mention `name` as a whole identifier (not as a substring of
/// a longer one)? Used by the T5 stripped-secret notice; a false positive
/// costs one advisory line on an already-failing command, a false negative
/// hides the reason the command failed — so err towards matching.
fn references_env_name(script: &str, name: &str) -> bool {
    let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_';
    let mut from = 0;
    while let Some(pos) = script[from..].find(name) {
        let start = from + pos;
        let end = start + name.len();
        let before_ok = !script[..start].chars().next_back().is_some_and(is_ident);
        let after_ok = !script[end..].chars().next().is_some_and(is_ident);
        if before_ok && after_ok {
            return true;
        }
        from = end;
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn explicit_child_kills_signal_and_disarm_group_before_reaping() {
        let source = include_str!("bash.rs");
        let executor = source.split("pub(crate) async fn run_shell_command").nth(1).unwrap()
            .split("#[cfg(test)]").next().unwrap();
        let kills: Vec<_> = executor.match_indices("let _ = child.kill().await;").collect();
        assert_eq!(kills.len(), 2, "audit every new explicit kill path");
        for (offset, _) in kills {
            assert!(executor[..offset].trim_end().ends_with("group.kill_now();"));
        }
        assert!(executor.contains("let status = child.wait().await;"));
        let wait = executor.split("let status = child.wait().await;").nth(1).unwrap();
        assert!(wait.find("group.finished();").unwrap() < wait.find("status.map_err").unwrap());
        assert!(executor.find("let mut child = cmd.spawn()").unwrap()
            < executor.find("let mut group = KillGroupUnlessFinished::new").unwrap());
    }

    #[tokio::test]
    async fn canceled_launch_never_runs_payload() {
        let dir = tempfile::tempdir().unwrap();
        let marker = dir.path().join("must-not-exist");
        let token = crate::CancellationToken::new();
        token.cancel();
        let mut ctx = create_tool_context();
        ctx.capabilities.launch_cancel = Some(token);
        let error = BashTool.execute(json!({"command": format!("touch '{}'", marker.display())}), ctx)
            .await.unwrap_err().to_string();
        assert!(error.contains("canceled before launch"), "{error}");
        assert!(!marker.exists());
    }

    #[cfg(target_os = "linux")]
    fn own_cgroup() -> String {
        std::fs::read_to_string("/proc/self/cgroup")
            .unwrap_or_default()
            .trim()
            .to_string()
    }

    /// The command runs in its own systemd scope when the machine supports
    /// it, so an out-of-memory kill aimed at it cannot take the daemon's
    /// cgroup down with it (S348). Without a reachable user manager (CI
    /// containers), the command must still run, in this process's cgroup.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn bash_command_gets_its_own_scope_when_available() {
        if std::env::var("SYNAPS_TEST_REAL_SCOPES").as_deref() != Ok("1") { return; }
        let out = BashTool
            .execute(
                json!({ "command": "cat /proc/self/cgroup; echo pid=$$", "timeout": 30 }),
                create_tool_context(),
            )
            .await
            .unwrap();
        let child_cgroup = out.lines().next().unwrap_or_default().trim().to_string();
        assert!(child_cgroup.starts_with("0::/"), "cgroup v2 line: {out}");
        if crate::process_scope::launcher_for_env(None).is_some() {
            assert_ne!(
                child_cgroup,
                own_cgroup(),
                "the command must leave our cgroup"
            );
            assert!(child_cgroup.ends_with(".scope"), "{child_cgroup}");
            assert!(child_cgroup.contains("/app.slice/"), "{child_cgroup}");
        } else {
            assert_eq!(child_cgroup, own_cgroup(), "unwrapped fallback");
        }
    }

    /// A bash command's scope goes in `tool_scope_slice`, never in the
    /// daemon's slice; the probe carries the same `--slice`.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    #[serial_test::serial(synaps_base_dir)]
    async fn a_bash_command_is_scoped_in_the_tool_slice() {
        use crate::process_scope::test_support::{fake_env, fake_systemd_run, recorded};
        let base = crate::test_env::BaseDirGuard::new();
        let _scopes = crate::test_env::EnvVarGuard::remove("SYNAPS_PROCESS_SCOPES");
        std::fs::write(
            base.path().join("config"),
            "tool_scope_slice = t_tools.slice\ndaemon_scope_slice = d_daemon.slice\n",
        )
        .unwrap();
        let dir = tempfile::tempdir().unwrap();
        let fake = fake_systemd_run(dir.path());
        let mut env = fake_env(&fake);
        env.push(("PATH".to_string(), std::env::var("PATH").unwrap_or_default()));
        let mut ctx = create_tool_context();
        ctx.capabilities.env = Some(env);
        let out = BashTool
            .execute(json!({ "command": "echo scoped-run", "timeout": 30 }), ctx)
            .await
            .unwrap();
        assert!(out.contains("scoped-run"), "{out}");
        let launch = recorded(dir.path(), "launch.args");
        let slices: Vec<&String> = launch.iter().filter(|a| a.starts_with("--slice")).collect();
        assert_eq!(slices, ["--slice=t_tools.slice"], "{launch:?}");
        assert!(recorded(dir.path(), "probe.args").contains(&"--slice=t_tools.slice".to_string()));
    }

    /// A session environment rebuilt without the user-bus variables cannot
    /// reach systemd: the command starts unwrapped instead of failing.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn bash_command_with_a_rebuilt_env_lacking_the_user_bus_runs_unwrapped() {
        let mut ctx = create_tool_context();
        ctx.capabilities.env = Some(vec![(
            "PATH".to_string(),
            std::env::var("PATH").unwrap_or_default(),
        )]);
        let out = BashTool
            .execute(
                json!({ "command": "cat /proc/self/cgroup", "timeout": 30 }),
                ctx,
            )
            .await
            .unwrap();
        assert_eq!(out.lines().next().unwrap_or_default().trim(), own_cgroup());
    }

    #[cfg(target_os = "linux")]
    fn processes_named(name: &str) -> Vec<String> {
        let out = std::process::Command::new("pgrep")
            .args(["-f", name])
            .output()
            .unwrap();
        String::from_utf8_lossy(&out.stdout)
            .split_whitespace()
            .map(str::to_string)
            .collect()
    }

    /// A timed-out command takes everything it started with it, not just the
    /// shell (S348: a timed-out test run would leave all its workers running).
    /// Each child is renamed to the marker (`exec -a`), so a survivor is seen.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn bash_timeout_kills_the_whole_process_group() {
        let marker = format!("synaps-timeout-child-{}", std::process::id());
        let out = BashTool
            .execute(
                json!({
                    "command": format!("(exec -a {marker} sleep 300) & (exec -a {marker} sleep 300); wait"),
                    "timeout": 1
                }),
                create_tool_context(),
            )
            .await;
        let text = match out {
            Ok(s) => s,
            Err(e) => e.to_string(),
        };
        assert!(text.contains("timed out"), "{text}");
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
        while !processes_named(&marker).is_empty() && std::time::Instant::now() < deadline {
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
        let left = processes_named(&marker);
        if !left.is_empty() {
            let _ = std::process::Command::new("pkill")
                .args(["-f", &marker])
                .status();
        }
        assert!(left.is_empty(), "children survived the timeout: {left:?}");
    }

    /// A command that exits by itself keeps what it deliberately started in
    /// the background, as before: only abnormal endings kill the group.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn bash_normal_exit_leaves_a_background_job_running() {
        let marker = format!("synaps-background-job-{}", std::process::id());
        let out = BashTool
            .execute(
                json!({
                    "command": format!("(exec -a {marker} sleep 30) >/dev/null 2>&1 & echo started"),
                    "timeout": 10
                }),
                create_tool_context(),
            )
            .await
            .unwrap();
        assert!(out.contains("started"), "{out}");
        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
        let alive = processes_named(&marker);
        let _ = std::process::Command::new("pkill")
            .args(["-f", &marker])
            .status();
        assert!(
            !alive.is_empty(),
            "a deliberate background job must survive a normal exit"
        );
    }

    #[tokio::test]
    async fn bash_intermediary_handoff_conserves_bytes_under_large_output() {
        let before = bash_intermediary_snapshot();
        let tool = BashTool;
        let mut ctx = create_tool_context();
        ctx.limits.max_tool_buffer = 64 * 1024;
        let result = tool
            .execute(
                json!({
                    "command": "python3 -c \"import sys; sys.stdout.write('x' * 1048576)\"",
                    "timeout": 30
                }),
                ctx,
            )
            .await
            .unwrap();
        assert!(result.contains("output truncated"));

        // The counters are process-global and sibling tests run bash
        // concurrently, so a before/after delta is skewed by whatever a
        // sibling had mid-channel when `before` was read, and that skew
        // never rebalances. Assert the invariant that does hold: once
        // in-flight relays drain, every byte ever produced in this process
        // was consumed or dropped. Siblings only delay this; a leaked byte
        // keeps it false forever.
        let after = wait_handoff_settled().await;
        assert_eq!(after.retained_bytes, 0);
        assert!(after.accepted_bytes >= after.consumed_bytes);
        assert!(after.produced_bytes - before.produced_bytes >= 64 * 1024);
    }

    #[test]
    fn sanitizes_terminal_control_sequences_and_nuls() {
        let cleaned = sanitize_output("ok\x1b[2J\x00done");
        assert_eq!(cleaned, "okdone");
    }

    use super::super::test_helpers::create_tool_context;
    use crate::tools::Tool;
    use serde_json::json;

    #[test]
    fn test_bash_tool_schema() {
        let tool = BashTool;
        assert_eq!(tool.name(), "bash");
        assert!(!tool.description().is_empty());

        let params = tool.parameters();
        assert_eq!(params["type"], "object");
        assert!(params["properties"].is_object());
        assert!(params["required"].is_array());
    }

    #[tokio::test]
    async fn test_bash_tool_execution() {
        let tool = BashTool;

        // Test simple echo command
        let ctx = create_tool_context();
        let params = json!({
            "command": "echo hello"
        });

        let result = tool.execute(params, ctx).await.unwrap();
        assert!(result.contains("hello"));

        // Test timeout parameter with quick command
        let ctx = create_tool_context();
        let params = json!({
            "command": "sleep 1",
            "timeout": 2
        });

        let result = tool.execute(params, ctx).await;
        // Should succeed (1 second sleep with 2 second timeout)
        assert!(result.is_ok());

        // Test timeout with longer command
        let ctx = create_tool_context();
        let params = json!({
            "command": "sleep 3",
            "timeout": 1
        });

        let result = tool.execute(params, ctx).await;
        // Should timeout
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("timed out"));
    }

    #[tokio::test]
    async fn test_bash_tool_requested_timeout_is_clamped_by_max_timeout() {
        let tool = BashTool;
        let mut ctx = create_tool_context();
        ctx.limits.bash_max_timeout = 1;

        let params = json!({
            "command": "sleep 5; echo done",
            "timeout": 10
        });

        let result = tool.execute(params, ctx).await;
        assert!(
            result.unwrap_err().to_string().contains("timed out"),
            "requested timeout MUST be clamped by bash_max_timeout"
        );
    }

    fn prompt_channel() -> (
        crate::tools::SecretPromptHandle,
        tokio::sync::mpsc::UnboundedReceiver<crate::tools::SecretPromptRequest>,
    ) {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        (crate::tools::SecretPromptHandle::new(tx), rx)
    }

    /// Output that merely looks like a password prompt. The first line is
    /// what a diagnostic printing the tool's own command lines showed on
    /// the day this misfired: the old wrapper, prompt string included.
    const PROMPT_LOOKALIKES: &str = r#"printf '%s\n' "command sudo -S -p '[sudo] password required: ' \"\$@\"" >&2
printf '[sudo] password for x: ' >&2
printf 'Password: ' >&2
if read -r got; then echo "stdin gave: $got"; else echo stdin-eof; fi"#;

    /// Regression: text on stderr can no longer raise a password prompt,
    /// and nothing is ever written to the command's stdin (it is empty).
    #[tokio::test]
    async fn sudo_prompt_lookalike_output_raises_no_prompt_and_feeds_no_stdin() {
        let (handle, mut prompts) = prompt_channel();
        let mut ctx = create_tool_context();
        ctx.capabilities.secret_prompt = Some(handle);
        let started = std::time::Instant::now();
        let out = BashTool
            .execute(json!({"command": PROMPT_LOOKALIKES, "timeout": 30}), ctx)
            .await
            .unwrap();
        assert!(out.contains("stdin-eof"), "{out}");
        assert!(out.contains("[sudo] password for x: "), "it is only output: {out}");
        assert!(out.contains("password required: "), "{out}");
        assert!(prompts.try_recv().is_err(), "no prompt was raised");
        assert!(started.elapsed() < std::time::Duration::from_secs(10));
    }

    #[cfg(unix)]
    #[test]
    fn the_sudo_wrapper_asks_through_askpass_or_not_at_all() {
        let script = super::bash_script_with_secure_sudo("sudo id", true);
        assert_eq!(script, "sudo() {\n    command sudo -A \"$@\"\n}\nsudo id");
        let script = super::bash_script_with_secure_sudo("sudo id", false);
        assert_eq!(script, "sudo() {\n    command sudo -n \"$@\"\n}\nsudo id");
        for askpass in [true, false] {
            let script = super::bash_script_with_secure_sudo("x", askpass);
            assert!(!script.contains(" -S") && !script.contains("password"), "{script}");
        }
    }

    /// Without the broker (this test binary does not dispatch the helper),
    /// sudo is told never to ask: it fails with its own error, no prompt.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn without_askpass_sudo_never_asks() {
        let fake = tempfile::tempdir().unwrap();
        crate::tools::sudo_askpass::testing::write_fixtures(fake.path()).unwrap();
        let (handle, mut prompts) = prompt_channel();
        let mut ctx = create_tool_context();
        ctx.capabilities.secret_prompt = Some(handle);
        let command = format!(
            "export PATH=\"{}:$PATH\"; sudo echo ran; echo after:$?",
            fake.path().display()
        );
        let out = BashTool
            .execute(json!({"command": command, "timeout": 30}), ctx)
            .await
            .unwrap();
        assert!(out.contains("sudo: a password is required"), "{out}");
        assert!(out.contains("after:1") && !out.contains("ran\n"), "{out}");
        assert!(prompts.try_recv().is_err());
    }

    #[tokio::test]
    async fn test_bash_control_char_output_is_sanitized_and_bounded_in_deltas() {
        let tool = BashTool;
        let channel = crate::tools::output::delta_channel();
        let (delta_tx, mut delta_rx) = (channel.sender, channel.receiver);
        let mut ctx = create_tool_context();
        ctx.channels.tx_delta = Some(delta_tx);
        ctx.limits.max_tool_buffer = 256;

        let params = json!({
            "command": "python3 -c \"import sys; sys.stdout.buffer.write(b'clean\\x1b[2J\\x00' + b'A' * 2000); sys.stdout.flush()\"",
            "timeout": 30
        });

        let result = tool.execute(params, ctx).await.unwrap();
        let mut streamed = String::new();
        while let Some(delta) = delta_rx.try_drain() {
            streamed.push_str(&delta);
        }

        assert!(result.contains("[output truncated at 256]"));
        assert!(!result.contains('\u{1b}'));
        assert!(!result.contains('\0'));
        assert!(!streamed.contains('\u{1b}'));
        assert!(!streamed.contains('\0'));
        assert!(
            streamed.len() <= 2048,
            "streamed deltas must be bounded, got {} bytes",
            streamed.len()
        );
    }

    #[tokio::test]
    async fn test_bash_binary_output_is_sanitized() {
        let tool = BashTool;
        let ctx = create_tool_context();
        let params = json!({
            "command": "python3 -c \"import sys; sys.stdout.buffer.write(bytes(range(32)) + b'visible')\"",
            "timeout": 30
        });

        let result = tool.execute(params, ctx).await.unwrap();

        assert!(result.contains("visible"));
        assert!(!result.contains('\0'));
        assert!(!result.contains('\u{1b}'));
    }

    #[tokio::test]
    async fn test_bash_tool_timeout() {
        let tool = BashTool;
        let ctx = create_tool_context();

        let params = json!({
            "command": "sleep 10",
            "timeout": 1
        });

        let result = tool.execute(params, ctx).await;

        // Should timeout and return error
        assert!(result.is_err());
        let error = result.unwrap_err().to_string();
        assert!(error.contains("timed out"));
    }

    #[tokio::test]
    async fn test_bash_tool_failure() {
        let tool = BashTool;
        let ctx = create_tool_context();

        let params = json!({
            "command": "exit 1"
        });

        let result = tool.execute(params, ctx).await;

        // Should fail and return error
        assert!(result.is_err());
        let error = result.unwrap_err().to_string();
        assert!(error.contains("failed") || error.contains("exit"));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn bash_honours_capability_cwd_when_set() {
        let tmp = tempfile::TempDir::new().unwrap();
        let expected = tmp.path().canonicalize().unwrap();
        let mut ctx = create_tool_context();
        ctx.capabilities.cwd = Some(tmp.path().to_path_buf());
        let out = BashTool
            .execute(json!({"command": "pwd -P"}), ctx)
            .await
            .unwrap();
        assert_eq!(out.trim(), expected.to_string_lossy());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn bash_inherits_process_cwd_when_capability_cwd_is_none() {
        let expected = std::env::current_dir().unwrap().canonicalize().unwrap();
        let ctx = create_tool_context();
        assert!(ctx.capabilities.cwd.is_none());
        let out = BashTool
            .execute(json!({"command": "pwd -P"}), ctx)
            .await
            .unwrap();
        assert_eq!(out.trim(), expected.to_string_lossy());
    }

    #[test]
    fn references_env_name_is_word_bounded() {
        assert!(references_env_name("echo ${GH_TOKEN:?}", "GH_TOKEN"));
        assert!(references_env_name("echo $GH_TOKEN", "GH_TOKEN"));
        assert!(references_env_name("GH_TOKEN=x gh auth", "GH_TOKEN"));
        assert!(references_env_name("$env:GH_TOKEN", "GH_TOKEN"));
        assert!(!references_env_name("echo $GH_TOKEN_FILE", "GH_TOKEN"));
        assert!(!references_env_name("echo $MY_GH_TOKEN", "GH_TOKEN"));
        assert!(!references_env_name("gh auth status", "GH_TOKEN"));
    }

    /// T5 notice: non-zero exit + script references stripped var → notice.
    #[cfg(unix)]
    #[tokio::test]
    async fn bash_notice_on_stripped_secret_reference() {
        let warned = std::sync::Arc::new(std::sync::Mutex::new(
            std::collections::HashSet::<String>::new(),
        ));
        // --- case 1: non-zero exit + reference → notice
        let mut ctx = create_tool_context();
        ctx.capabilities.env_stripped = vec!["GH_TOKEN".into()];
        ctx.capabilities.env_warned = warned.clone();
        let err = BashTool
            .execute(json!({"command": "echo ${GH_TOKEN:?} 2>&1; exit 1"}), ctx)
            .await
            .unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("note: $GH_TOKEN was stripped"),
            "notice must name the var: {msg}"
        );

        // --- case 2: zero exit → no notice
        let mut ctx2 = create_tool_context();
        ctx2.capabilities.env_stripped = vec!["GH_TOKEN".into()];
        ctx2.capabilities.env_warned = warned.clone();
        let out = BashTool
            .execute(json!({"command": "echo $GH_TOKEN; exit 0"}), ctx2)
            .await
            .unwrap();
        assert!(
            !out.contains("note:"),
            "zero exit must not produce a notice: {out}"
        );

        // --- case 3: second failure → no duplicate (same Arc)
        let mut ctx3 = create_tool_context();
        ctx3.capabilities.env_stripped = vec!["GH_TOKEN".into()];
        ctx3.capabilities.env_warned = warned.clone();
        let err2 = BashTool
            .execute(json!({"command": "echo ${GH_TOKEN}; exit 1"}), ctx3)
            .await
            .unwrap_err();
        let msg2 = format!("{err2}");
        assert!(
            !msg2.contains("note: $GH_TOKEN was stripped"),
            "dedup must suppress the second notice: {msg2}"
        );
    }
}

/// Issue #286: a multi-byte character split across two reads must come back
/// whole, not as U+FFFD.
#[cfg(test)]
mod utf8_chunk_tests {
    use super::*;
    use crate::tools::Tool;
    use serde_json::json;
    use std::collections::VecDeque;
    use std::pin::Pin;
    use std::task::{Context, Poll};

    /// Yields exactly the given chunks, one per `read`, then EOF.
    struct ChunkedReader(VecDeque<Vec<u8>>);

    impl tokio::io::AsyncRead for ChunkedReader {
        fn poll_read(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &mut tokio::io::ReadBuf<'_>,
        ) -> Poll<std::io::Result<()>> {
            if let Some(chunk) = self.0.pop_front() {
                assert!(chunk.len() <= buf.remaining(), "test chunk larger than read buffer");
                buf.put_slice(&chunk);
            }
            Poll::Ready(Ok(()))
        }
    }

    async fn forward_chunks(chunks: Vec<Vec<u8>>, is_stderr: bool) -> String {
        let (tx, mut rx) = tokio::sync::mpsc::channel(1024);
        forward_output(ChunkedReader(chunks.into()), is_stderr, tx).await;
        let mut out = String::new();
        while let Some((stderr, chunk)) = rx.recv().await {
            let msg = chunk.consume();
            assert_eq!(stderr, is_stderr);
            out.push_str(&msg);
        }
        out
    }

    #[tokio::test]
    async fn characters_split_at_every_offset_survive_both_streams() {
        for ch in ['é', '▀', '😀'] {
            let text = format!("a{ch}b{ch}{ch}c");
            let bytes = text.as_bytes();
            for split in 1..bytes.len() {
                for is_stderr in [false, true] {
                    let out = forward_chunks(
                        vec![bytes[..split].to_vec(), bytes[split..].to_vec()],
                        is_stderr,
                    )
                    .await;
                    assert!(!out.contains('\u{FFFD}'), "{ch:?} split at {split}: {out:?}");
                    assert_eq!(out.as_bytes(), bytes, "{ch:?} split at {split}");
                }
            }
        }
    }

    #[tokio::test]
    async fn one_byte_reads_reassemble_every_character() {
        let text = "é▀😀 mixed ascii ✓ 日本語";
        let chunks = text.bytes().map(|b| vec![b]).collect();
        assert_eq!(forward_chunks(chunks, false).await, text);
    }

    #[tokio::test]
    async fn genuinely_invalid_bytes_still_become_replacement_characters() {
        assert_eq!(forward_chunks(vec![b"ok\xffok".to_vec()], false).await, "ok\u{FFFD}ok");
        // A lead byte followed by a non-continuation byte in the next read.
        assert_eq!(
            forward_chunks(vec![b"a\xe2".to_vec(), b"Xb".to_vec()], false).await,
            "a\u{FFFD}Xb"
        );
        // A stray continuation byte at the start of a read.
        assert_eq!(
            forward_chunks(vec![b"a".to_vec(), b"\x80b".to_vec()], false).await,
            "a\u{FFFD}b"
        );
    }

    #[tokio::test]
    async fn incomplete_sequence_at_eof_is_flushed_not_dropped() {
        assert_eq!(forward_chunks(vec![b"ab\xe2\x96".to_vec()], false).await, "ab\u{FFFD}");
        assert_eq!(
            forward_chunks(vec![b"ab".to_vec(), b"\xf0\x9f".to_vec()], true).await,
            "ab\u{FFFD}"
        );
    }

    /// A consumer that gives up (timeout, cancelled password prompt) drops
    /// the receiver with chunks still queued. Those bytes must be counted as
    /// dropped, or the process-wide accounting never settles again.
    #[tokio::test]
    async fn chunks_still_queued_when_the_receiver_goes_away_count_as_dropped() {
        let (tx, rx) = tokio::sync::mpsc::channel(16);
        let chunks: Vec<Vec<u8>> = (0..8).map(|_| b"queued".to_vec()).collect();
        forward_output(ChunkedReader(chunks.into()), false, tx).await;
        let before = bash_intermediary_snapshot();
        drop(rx);
        let after = wait_handoff_settled().await;
        assert!(after.dropped_bytes - before.dropped_bytes >= 8 * 6);
    }

    /// A password prompt has no trailing newline; it must be forwarded as soon
    /// as it is read, not held back waiting for more output or EOF.
    #[tokio::test]
    async fn prompt_without_newline_is_forwarded_before_eof() {
        let (mut writer, reader) = tokio::io::duplex(4096);
        let (tx, mut rx) = tokio::sync::mpsc::channel(16);
        let task = tokio::spawn(forward_output(reader, true, tx));
        use tokio::io::AsyncWriteExt;
        writer.write_all("[sudo] password for x: ".as_bytes()).await.unwrap();
        let (is_stderr, chunk) =
            tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv())
                .await
                .expect("prompt must arrive without EOF")
                .unwrap();
        let msg = chunk.consume();
        assert!(is_stderr);
        assert_eq!(msg, "[sudo] password for x: ");
        drop(writer);
        task.await.unwrap();
    }

    /// Through the real tool: more than 1 KiB of 3-byte characters on both
    /// streams. 1024 is not a multiple of 3, so the reads split characters.
    #[tokio::test]
    async fn bash_tool_output_over_1kib_keeps_multibyte_characters_whole() {
        let channel = crate::tools::output::delta_channel();
        let (delta_tx, mut delta_rx) = (channel.sender, channel.receiver);
        let mut ctx = super::super::test_helpers::create_tool_context();
        ctx.channels.tx_delta = Some(delta_tx);
        let result = BashTool
            .execute(json!({"command": "printf '▀%.0s' {1..2000}", "timeout": 30}), ctx)
            .await
            .unwrap();
        let mut streamed = String::new();
        while let Some(delta) = delta_rx.try_drain() {
            streamed.push_str(&delta);
        }
        let expected = "▀".repeat(2000);
        assert!(!result.contains('\u{FFFD}'), "result has U+FFFD");
        assert_eq!(result, expected);
        assert!(!streamed.contains('\u{FFFD}'), "deltas have U+FFFD");
        assert!(expected.starts_with(&streamed) && !streamed.is_empty());

        let ctx = super::super::test_helpers::create_tool_context();
        let err = BashTool
            .execute(
                json!({"command": "python3 -c \"import sys; sys.stderr.write(('▀'*119+'\\n')*45)\"; exit 3", "timeout": 30}),
                ctx,
            )
            .await
            .unwrap_err()
            .to_string();
        assert!(!err.contains('\u{FFFD}'), "stderr has U+FFFD: {err}");
        assert!(err.contains(&("▀".repeat(119) + "\n").repeat(45)), "{err}");
    }
}