mahbot 0.10.4

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Background shell sessions (Full shell roles only).
//!
//! An agent can launch a long-running non-interactive command that keeps running after the
//! initiating tool call returns. Output is written RAW (no profile transforms) to
//! a file in the temp area's `.agent` directory; the agent reads progress with the read tool and
//! stops the session via the shell tool's `stop` argument. The file holds a program's own bytes,
//! so the read tool reads it the way the shell reads a program's output ([`is_output_file`]).
//! Sessions are strictly agent-scoped: the registry lives inside the [`crate::Agent`] and is
//! force-killed on agent teardown ([`BackgroundSessions::terminate_all`]).
//!
//! # Watchdog (Unix)
//!
//! A child-side watcher process keeps the process group alive only while the daemon is. A pipe
//! is created with both ends `O_CLOEXEC`; the read end becomes the watcher's stdin and the write
//! end is held by the daemon. The watcher blocks reading stdin; when the write end closes —
//! daemon crash, or the session finishing — it SIGKILLs the whole process group. The watcher is
//! the group leader (`process_group(0)`) and the command joins its group, so one `kill(-pgid)`
//! reaches every descendant. That guarantees no orphaned processes even on a hard daemon crash,
//! with no shutdown hook (destructors do not run on SIGKILL/SIGSEGV/OOM/`process::exit`, and the
//! platform lacks parent-death signals). The same watchdog covers the launch window: a launch
//! future aborted between spawn and registration drops the write end, the watcher fires, and the
//! group dies — no kill-on-drop guard is needed.
//!
//! # Windows
//!
//! There is no watchdog and no process group: a session's whole process tree is held in a job
//! object ([`super::tree::Tree`]) — created at launch, inherited by every descendant, ended on
//! stop, on teardown, by the OS when the daemon dies (`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`), and
//! when the command exits on its own, which is the unix watcher's counterpart. A job that could
//! not be created or assigned leaves the session with exactly the treatment it had before jobs
//! existed — the direct child alone; `tree` records that fail-open policy and its limits.
//!
//! The launch-failure probe is Unix-shell-specific: cmd.exe exits 1 (not 126/127) for a missing
//! or non-executable command, so a failed launch there surfaces as a successful session whose
//! output file holds the cmd.exe error and `[exit status: 1]` (accepted deviation).

use std::collections::HashMap;
use std::fs::{File, OpenOptions};
#[cfg(unix)]
use std::os::fd::FromRawFd;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use super::ShellMode;
#[cfg(not(unix))]
use super::tree::{RunOwner, Tree};
use super::windows_line::{Executed, Written};
use crate::util::UnwrapPoison;

/// Watcher script: ignore SIGTERM (the daemon owns the graceful two-stage stop), block on
/// stdin until EOF, then SIGKILL the caller's process group.
#[cfg(unix)]
const WATCHER_SCRIPT: &str = "trap '' TERM; cat >/dev/null; kill -s KILL 0";

/// Bounded early-exit launch probe: 126/127 exits within this window are synchronous launch
/// failures. Every other early exit — a legitimate non-zero one included — is a successful
/// launch surfaced via the exit-status annotation.
const LAUNCH_PROBE: Duration = Duration::from_millis(250);
const POLL_INTERVAL: Duration = Duration::from_millis(25);
const WAITER_POLL: Duration = Duration::from_millis(50);
/// Grace between SIGTERM and SIGKILL in the two-stage stop.
#[cfg_attr(not(unix), expect(dead_code))] // only the Unix two-stage stop has a grace
const STOP_GRACE: Duration = Duration::from_secs(5);
/// How long `stop()` waits for the waiter to append the exit annotation after the SIGKILL.
const STOP_ANNOTATION_WAIT: Duration = Duration::from_secs(2);
/// Output-file name attempts before giving up (create_new never overwrites).
const MAX_OUTPUT_NAME_ATTEMPTS: usize = 16;
/// How many leading bytes of the output file the launch-failure tool error quotes.
const FAILURE_OUTPUT_PREFIX_BYTES: usize = 400;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StopResult {
    /// The stop ran (or the process was already dead).
    Stopped,
    /// The session had already finished before the stop arrived — no-op.
    AlreadyFinished,
}

/// Agent-scoped registry of background shell sessions. State is owned by the agent (dropped
/// with it) and reachable from the synchronous teardown path for the teardown kill; the
/// tool-batch context carries only an `Arc` handle.
pub(crate) struct BackgroundSessions {
    inner: std::sync::Mutex<HashMap<PathBuf, SessionEntry>>,
}

impl Default for BackgroundSessions {
    fn default() -> Self {
        Self {
            inner: std::sync::Mutex::new(HashMap::new()),
        }
    }
}

/// One live (or finished) background session, keyed by its output-file path.
struct SessionEntry {
    /// The launched command child, shared with the waiter task (which reaps it) and the
    /// stop/teardown paths. Never taken out after launch — the waiter polls `try_wait` in place.
    /// A `std::sync::Mutex` suffices: every critical section is a short synchronous call, never
    /// held across an await, which also makes the synchronous teardown kill reliable.
    command: Arc<std::sync::Mutex<tokio::process::Child>>,
    /// Windows: the job the session's whole process tree is in — ended on stop, on teardown, by
    /// the OS if the daemon dies, and by the waiter when the command exits.
    #[cfg(not(unix))]
    tree: Tree,
    /// Watcher child (Unix), reaped by the waiter after the command exits.
    #[cfg(unix)]
    watcher: Option<tokio::process::Child>,
    /// Write end of the daemon→watcher lifeline pipe. EOF on the watcher's stdin is what makes
    /// it fire.
    #[cfg(unix)]
    write_end: Option<std::os::fd::OwnedFd>,
    /// Process-group id == the watcher's PID (Unix), used for group kills.
    #[cfg(unix)]
    pgid: u32,
    /// The command exited during the launch probe with a non-launch-failure status.
    early_status: Option<std::process::ExitStatus>,
    /// Set by the waiter after the exit annotation is appended — the only completion signal.
    finished: Arc<AtomicBool>,
}

/// The command a background session runs: the shell, or this service's own image when the command
/// is one call of it ([`super::plan::plan_for_command`]). The image is spawned directly rather than
/// through a shell, so the session waits for it and reports the child's own status and output.
/// `Err` is the launch error for a command that names the image in a shape the runner cannot wire
/// as one command: a background command must fail at launch, never report a false completion. Only
/// the shell's arm measures anything: the text handed to the interpreter is this platform's one
/// line, so a reading past the platform's command line is refused here
/// ([`super::windows_line::check_command_line`]). A call of this service's own image is spawned
/// from its own argv, so nothing is measured for it. The returned streams are the ones the
/// command's own redirect tokens took over; the caller wires the session's own stdio for the rest,
/// which is where a `2>&1` whose stdout the session still owns belongs.
fn own_image_command(
    executed: Executed<'_>,
    written: Written<'_>,
    workspace_root: &Path,
    mode: ShellMode,
) -> Result<(tokio::process::Command, Vec<super::Stream>), String> {
    match super::plan::plan_for_command(executed, written, workspace_root) {
        super::plan::OwnImage::None => {
            super::windows_line::check_command_line(executed.0, super::SHELL_PLATFORM, mode)?;
            Ok((
                super::build_shell_command(executed.0, workspace_root),
                Vec::new(),
            ))
        }
        super::plan::OwnImage::Direct(plan) => {
            let Some((args, redirects, cwd)) = plan.direct_own() else {
                // A line the runner's decomposition read as a chain: a background session launches
                // one command, so this fails the launch rather than report a false completion.
                return Err(super::plan::refusal_message(
                    "the command could not be read as a single call of `mahbot`",
                ));
            };
            let mut cmd = super::build_program_command(&plan.exe, args, cwd);
            let applied = super::plan::apply_redirects(&mut cmd, redirects, cwd).map_err(|e| {
                format!(
                    "Failed to start background command.\ncommand: {}\nreason: {e}",
                    written.0
                )
            })?;
            Ok((cmd, applied.streams))
        }
        super::plan::OwnImage::Refused(cause) => Err(super::plan::refusal_message(&cause)),
    }
}

impl BackgroundSessions {
    /// Launch `executed` in the background. Returns the output-file path.
    ///
    /// `executed` is the text the platform will run and `written` the line the agent wrote, which
    /// is what a launch failure quotes — the two differ on Windows alone ([`super::windows_line`]).
    /// `mode` decides the words of the remedy a refusal ends with.
    ///
    /// The command is spawned detached from the tool call: stdout and stderr are redirected (RAW)
    /// into the output file, stdin is null, and the whole process tree is contained — in its own
    /// process group on Unix, in a job object on Windows. Launch failures are returned as `Err`
    /// synchronously, never a silent empty file.
    pub(super) async fn launch(
        self: &Arc<Self>,
        executed: Executed<'_>,
        written: Written<'_>,
        workspace_root: &Path,
        mode: ShellMode,
    ) -> Result<PathBuf, String> {
        let (output_path, out_file) = create_bg_output_file()
            .map_err(|e| format!("Failed to create background output file: {e}"))?;
        // Owner-deletes-at-end: attribute the output file to the calling agent so `run_agent`'s
        // end-of-run cleanup removes it — `terminate_all` kills the tree but leaves the file.
        super::record_spill_owner(output_path.clone());

        // A command that names this service's own image cannot be left to the shell: a session
        // must report the image's own status, so a lone own-image call is spawned directly and any
        // other shape that names the image fails at launch.
        let (mut cmd, taken) = match own_image_command(executed, written, workspace_root, mode) {
            Ok(command) => command,
            Err(reason) => {
                let _ = std::fs::remove_file(&output_path);
                return Err(reason);
            }
        };
        let stdout_file = out_file.try_clone().map_err(|e| {
            let _ = std::fs::remove_file(&output_path);
            format!("Failed to set up background output: {e}")
        })?;
        let stderr_file = out_file.try_clone().map_err(|e| {
            let _ = std::fs::remove_file(&output_path);
            format!("Failed to set up background output: {e}")
        })?;
        // The session's own wiring, for the streams the command's redirect tokens did not take.
        if !taken.contains(&super::Stream::Stdin) {
            cmd.stdin(Stdio::null());
        }
        if !taken.contains(&super::Stream::Stdout) {
            cmd.stdout(Stdio::from(stdout_file));
        }
        if !taken.contains(&super::Stream::Stderr) {
            cmd.stderr(Stdio::from(stderr_file));
        }

        // Windows: the session's whole-tree containment, created before the spawn and dropped on
        // every launch path that never registers the session.
        #[cfg(not(unix))]
        let mut tree = Tree::new(RunOwner::Agent);

        #[cfg(unix)]
        let watchdog = match WatchdogSetup::spawn(&mut cmd, &output_path) {
            Ok(w) => w,
            Err(e) => {
                let _ = std::fs::remove_file(&output_path);
                return Err(e);
            }
        };

        let mut cmd_child = match cmd.spawn() {
            Ok(c) => c,
            Err(e) => {
                #[cfg(unix)]
                watchdog.abort().await;
                let _ = std::fs::remove_file(&output_path);
                return Err(format!("Failed to start background command: {e}"));
            }
        };

        #[cfg(not(unix))]
        if let Some(pid) = cmd_child.id() {
            tree.attach(pid);
        }

        // The 126/127 detection is Unix-shell-specific — cmd.exe exits 1 for a missing command,
        // so a failed launch there surfaces as a session whose file holds the cmd.exe error.
        let early_status = match probe_command(&mut cmd_child).await {
            Ok(Some(status)) if matches!(status.code(), Some(126 | 127)) => {
                let prefix = read_output_prefix(&output_path, FAILURE_OUTPUT_PREFIX_BYTES);
                #[cfg(unix)]
                watchdog.abort().await;
                let _ = std::fs::remove_file(&output_path);
                let prefix_msg = prefix
                    .filter(|p| !p.is_empty())
                    .map(|p| format!("\noutput: {p}"))
                    .unwrap_or_default();
                return Err(format!(
                    "Failed to start background command.\n\
                     command: {}\n\
                     reason: command not found or not executable (exit status {}).{prefix_msg}",
                    written.0,
                    status.code().unwrap_or(-1)
                ));
            }
            Ok(Some(status)) => Some(status),
            Ok(None) => None,
            Err(e) => {
                #[cfg(unix)]
                watchdog.abort().await;
                let _ = std::fs::remove_file(&output_path);
                return Err(e);
            }
        };

        let entry = SessionEntry {
            command: Arc::new(std::sync::Mutex::new(cmd_child)),
            #[cfg(unix)]
            watcher: Some(watchdog.watcher_child),
            #[cfg(unix)]
            write_end: Some(watchdog.write_end),
            #[cfg(unix)]
            pgid: watchdog.pgid,
            #[cfg(not(unix))]
            tree,
            early_status,
            finished: Arc::new(AtomicBool::new(false)),
        };
        self.inner
            .lock()
            .unwrap_poison()
            .insert(output_path.clone(), entry);
        self.spawn_waiter(&output_path);
        Ok(output_path)
    }

    /// Stop the session whose output file is `output_path`. On Unix a two-stage stop: SIGTERM →
    /// grace → SIGKILL to the process group; on Windows the whole tree ends at once. Stopping a
    /// finished session is a no-op guarded by the finished flag (PID-reuse safety).
    pub(crate) async fn stop(self: &Arc<Self>, output_path: &Path) -> Result<StopResult, String> {
        #[cfg(unix)]
        {
            let (pgid, finished) = {
                let guard = self.inner.lock().unwrap_poison();
                let entry = guard.get(output_path).ok_or_else(|| {
                    format!(
                        "No background session found for output file: {}",
                        output_path.display()
                    )
                })?;
                (entry.pgid, entry.finished.clone())
            };
            if finished.load(Ordering::SeqCst) {
                return Ok(StopResult::AlreadyFinished);
            }
            super::kill_process_group(pgid, libc::SIGTERM);
            tokio::time::sleep(stop_grace()).await;
            // Re-check `finished` before the second stage: a command that died during the grace has
            // already set it, and the watcher (whose PID is the PGID) is about to exit — its PID
            // could be recycled before the SIGKILL lands.
            if !finished.load(Ordering::SeqCst) {
                super::kill_process_group(pgid, libc::SIGKILL);
            }
            wait_for_finished(&finished, stop_annotation_wait()).await;
            Ok(StopResult::Stopped)
        }
        #[cfg(not(unix))]
        {
            let (command, tree, finished) = {
                let guard = self.inner.lock().unwrap_poison();
                let entry = guard.get(output_path).ok_or_else(|| {
                    format!(
                        "No background session found for output file: {}",
                        output_path.display()
                    )
                })?;
                (
                    entry.command.clone(),
                    entry.tree.clone(),
                    entry.finished.clone(),
                )
            };
            if finished.load(Ordering::SeqCst) {
                return Ok(StopResult::AlreadyFinished);
            }
            // Windows has no SIGTERM equivalent: a stop ends the whole tree at once. The direct
            // child is the fallback for a session whose job did not end its tree.
            if !tree.terminate() {
                let mut g = command.lock().unwrap_poison();
                let _ = g.start_kill();
            }
            wait_for_finished(&finished, stop_annotation_wait()).await;
            Ok(StopResult::Stopped)
        }
    }

    /// Force-kill every live session (no grace), called synchronously from the agent teardown
    /// path ([`crate::Agent::drop`]). Finished sessions are skipped; their waiters reaped them.
    pub(crate) fn terminate_all(&self) {
        let targets: Vec<_> = {
            let mut guard = self.inner.lock().unwrap_poison();
            guard
                .iter_mut()
                .filter(|(_, e)| !e.finished.load(Ordering::SeqCst))
                .map(|(_, e)| {
                    #[cfg(unix)]
                    {
                        (e.pgid, e.write_end.take())
                    }
                    #[cfg(not(unix))]
                    {
                        (e.command.clone(), e.tree.clone())
                    }
                })
                .collect()
        };
        for target in targets {
            #[cfg(unix)]
            {
                super::kill_process_group(target.0, libc::SIGKILL);
                // Closing the lifeline makes the watcher exit.
                drop(target.1);
            }
            #[cfg(not(unix))]
            {
                // Blocking lock: every critical section on this mutex is a short synchronous call,
                // so it cannot deadlock — and a failing try_lock would leak the direct child.
                if !target.1.terminate() {
                    let mut g = target.0.lock().unwrap_poison();
                    let _ = g.start_kill();
                }
            }
        }
    }

    #[cfg(test)]
    pub(crate) fn contains(&self, path: &Path) -> bool {
        self.inner.lock().unwrap_poison().contains_key(path)
    }

    #[cfg(test)]
    pub(crate) fn is_finished(&self, path: &Path) -> bool {
        self.inner
            .lock()
            .unwrap_poison()
            .get(path)
            .is_some_and(|e| e.finished.load(Ordering::SeqCst))
    }

    /// Spawn the per-session waiter task: poll the command child until it exits, append the
    /// unconditional exit-status annotation, set the finished flag, end whatever the session left
    /// behind (the Unix watcher, whose lifeline close kills the leftover group members; Windows
    /// ends the tree), and reap the watcher child. Detached — it outlives the agent by a few
    /// instants on teardown to reap the children the teardown kill signalled.
    fn spawn_waiter(self: &Arc<Self>, output_path: &Path) {
        // The waiter outlives the agent on teardown, so it holds its own handle on the registry.
        #[cfg(unix)]
        let sessions = self.clone();
        let output_path = output_path.to_path_buf();
        // Everything the waiter needs up front: the shared command and finished handles, and —
        // Windows — the job, which the waiter owns, since terminating it is what ends whatever the
        // session left behind. The unix arm takes the watcher and its lifeline later.
        let guard = self.inner.lock().unwrap_poison();
        let entry = guard.get(&output_path).expect("session just registered");
        let command = entry.command.clone();
        let finished = entry.finished.clone();
        let early_status = entry.early_status;
        #[cfg(not(unix))]
        let tree = entry.tree.clone();
        drop(guard);

        tokio::spawn(async move {
            let mut status = early_status;
            if status.is_none() {
                loop {
                    let exited = {
                        let mut g = command.lock().unwrap_poison();
                        g.try_wait().ok().flatten()
                    };
                    if let Some(s) = exited {
                        status = Some(s);
                        break;
                    }
                    tokio::time::sleep(WAITER_POLL).await;
                }
            }
            let status = status.expect("background command status determined");

            // The exit-status annotation is the only completion signal — appended unconditionally.
            append_exit_annotation(&output_path, status);
            finished.store(true, Ordering::SeqCst);

            #[cfg(unix)]
            {
                let (watcher, write_end) = {
                    let mut guard = sessions.inner.lock().unwrap_poison();
                    let entry = guard
                        .get_mut(&output_path)
                        .expect("session still registered");
                    (entry.watcher.take(), entry.write_end.take())
                };
                drop(write_end); // EOF → watcher kills leftover group members → exits
                if let Some(mut w) = watcher {
                    let _ = w.wait().await;
                }
            }

            // Windows: the command exited on its own, so nothing the session left behind runs on.
            #[cfg(not(unix))]
            tree.terminate();
        });
    }
}

/// Spawned process-group topology for a background session (Unix):
///
/// ```text
/// daemon (mahbot)
///  ├── pipe write end (held by the session entry; CLOEXEC)
///  ├── [watcher child] sh -c WATCHER_SCRIPT   ← group leader (PGID = its PID)
///  │     └─ stdin = pipe read end (CLOEXEC); blocks until EOF, then SIGKILLs
///  │        the group via `kill -s KILL 0`
///  └── [command child] sh -c "command"        ← joins the watcher's group
/// └─ stdout/stderr → output file; stdin → /dev/null ```
#[cfg(unix)]
struct WatchdogSetup {
    watcher_child: tokio::process::Child,
    write_end: std::os::fd::OwnedFd,
    pgid: u32,
}

#[cfg(unix)]
impl WatchdogSetup {
    /// Create the lifeline pipe and spawn the watcher as group leader, then point `cmd` at the
    /// watcher's process group.
    fn spawn(cmd: &mut tokio::process::Command, output_path: &Path) -> Result<Self, String> {
        let (read_end, write_end) = make_lifeline_pipe().map_err(|e| {
            let _ = std::fs::remove_file(output_path);
            format!("Failed to create background lifeline pipe: {e}")
        })?;
        let mut watcher_cmd = tokio::process::Command::new("sh");
        watcher_cmd
            .arg("-c")
            .arg(WATCHER_SCRIPT)
            .process_group(0)
            .stdin(Stdio::from(read_end))
            .stdout(Stdio::null())
            .stderr(Stdio::null());
        let watcher_child = match watcher_cmd.spawn() {
            Ok(c) => c,
            Err(e) => {
                let _ = std::fs::remove_file(output_path);
                return Err(format!("Failed to spawn background watchdog: {e}"));
            }
        };
        let pgid = watcher_child
            .id()
            .expect("watcher PID available after spawn");
        let pgid_signed: libc::pid_t = pgid.try_into().expect("PGID fits in pid_t");
        cmd.process_group(pgid_signed);
        Ok(Self {
            watcher_child,
            write_end,
            pgid,
        })
    }

    /// Kill the watcher's group, close the lifeline, and reap the watcher — launch-failure paths.
    async fn abort(self) {
        super::kill_process_group(self.pgid, libc::SIGKILL);
        drop(self.write_end);
        let mut w = self.watcher_child;
        let _ = w.wait().await;
    }
}

/// Create a pipe with both ends `O_CLOEXEC`: it must never leak into the command or the
/// watcher's children, or EOF would never arrive.
#[cfg(unix)]
fn make_lifeline_pipe() -> std::io::Result<(std::os::fd::OwnedFd, std::os::fd::OwnedFd)> {
    let mut fds = [0i32; 2];
    // SAFETY: pipe(2) writes two valid fds into the array on success.
    let ret = unsafe { libc::pipe(fds.as_mut_ptr()) };
    if ret != 0 {
        return Err(std::io::Error::last_os_error());
    }
    for fd in fds {
        // SAFETY: fds are valid pipe fds; F_GETFD/F_SETFD are standard.
        let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
        if flags < 0 {
            return Err(std::io::Error::last_os_error());
        }
        let ret = unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) };
        if ret != 0 {
            return Err(std::io::Error::last_os_error());
        }
    }
    // SAFETY: fds[0] and fds[1] are valid, owned pipe fds.
    Ok(unsafe {
        (
            std::os::fd::OwnedFd::from_raw_fd(fds[0]),
            std::os::fd::OwnedFd::from_raw_fd(fds[1]),
        )
    })
}

/// Grace between SIGTERM and SIGKILL in the two-stage stop. Env-overridable for tests.
#[cfg_attr(not(unix), expect(dead_code))]
fn stop_grace() -> Duration {
    crate::util::env_duration_secs("MAHBOT_BG_STOP_GRACE_SECS", STOP_GRACE.as_secs())
}

/// How long `stop()` waits for the exit annotation after the kill. Env-overridable for tests.
fn stop_annotation_wait() -> Duration {
    crate::util::env_duration_secs(
        "MAHBOT_BG_ANNOTATION_WAIT_SECS",
        STOP_ANNOTATION_WAIT.as_secs(),
    )
}

/// Create the output file with create_new semantics in the shared `.agent` temp directory. The
/// `bg_*` name shape is flat and outside the `spill_*` namespace, so spill detection never
/// mistakes it for a spill file and the temp cleaners reclaim it like any other leftover.
fn create_bg_output_file() -> std::io::Result<(PathBuf, File)> {
    let dir = super::agent_temp_dir().ok_or_else(|| {
        std::io::Error::new(std::io::ErrorKind::NotFound, "agent temp dir unavailable")
    })?;
    for _ in 0..MAX_OUTPUT_NAME_ATTEMPTS {
        let name = format!(
            "{OUTPUT_FILE_PREFIX}{:04x}{OUTPUT_FILE_SUFFIX}",
            rand::random::<u16>()
        );
        let path = dir.join(name);
        match OpenOptions::new().write(true).create_new(true).open(&path) {
            Ok(file) => return Ok((path, file)),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
            Err(e) => return Err(e),
        }
    }
    Err(std::io::Error::new(
        std::io::ErrorKind::AlreadyExists,
        "could not allocate a unique background output file name",
    ))
}

// The name shape [`create_bg_output_file`] puts a session's output in: `bg_XXXX.out` (4 hex
// digits) directly inside the shared `.agent` temp directory.
const OUTPUT_FILE_PREFIX: &str = "bg_";
const OUTPUT_FILE_SUFFIX: &str = ".out";
const OUTPUT_DIR_NAME: &str = ".agent";

/// Whether `path` is named like one of this module's own output files — the reason the read tool
/// may read a session's output as a program's output ([`super::decode_session_output`]).
///
/// The names are the whole test, and the directory is deliberately not compared against the temp
/// root, which would mean canonicalising both sides.
pub(super) fn is_output_file(path: &Path) -> bool {
    let shaped = path
        .file_name()
        .and_then(|name| name.to_str())
        .and_then(|name| name.strip_prefix(OUTPUT_FILE_PREFIX))
        .and_then(|name| name.strip_suffix(OUTPUT_FILE_SUFFIX))
        .is_some_and(|hex| hex.len() == 4 && hex.chars().all(|c| c.is_ascii_hexdigit()));
    shaped
        && path
            .parent()
            .and_then(|dir| dir.file_name())
            .and_then(|dir| dir.to_str())
            .is_some_and(|dir| dir == OUTPUT_DIR_NAME)
}

/// Bounded early-exit probe: `Ok(Some(status))` = the command exited within the window (already
/// reaped); `Ok(None)` = still running after it.
async fn probe_command(
    cmd_child: &mut tokio::process::Child,
) -> Result<Option<std::process::ExitStatus>, String> {
    let deadline = Instant::now() + LAUNCH_PROBE;
    loop {
        match cmd_child.try_wait() {
            Ok(Some(status)) => return Ok(Some(status)),
            Ok(None) => {
                if Instant::now() >= deadline {
                    return Ok(None);
                }
                tokio::time::sleep(POLL_INTERVAL).await;
            }
            Err(e) => {
                return Err(format!("Failed to probe background command: {e}"));
            }
        }
    }
}

/// Append the unconditional exit-status annotation — the only completion signal for background
/// sessions — in the shared foreground format ([`format_exit_status_note`]).
fn append_exit_annotation(output_path: &Path, status: std::process::ExitStatus) {
    let note = super::format_exit_status_note(status.code());
    match OpenOptions::new().append(true).open(output_path) {
        Ok(mut f) => {
            use std::io::Write;
            let _ = writeln!(f, "\n{note}");
        }
        Err(e) => {
            tracing::warn!(
                path = %output_path.display(),
                err = %e,
                "Failed to append background exit annotation"
            );
        }
    }
}

/// Read up to `max_bytes` from the START of the output file, decoded as a program's output
/// ([`super::windows_text::decode`]), for the launch-failure tool error.
fn read_output_prefix(path: &Path, max_bytes: usize) -> Option<String> {
    use std::io::Read;
    let mut f = File::open(path).ok()?;
    let mut buf = Vec::new();
    let mut chunk = [0u8; 256];
    while buf.len() < max_bytes {
        let n = f.read(&mut chunk).ok()?;
        if n == 0 {
            break;
        }
        buf.extend_from_slice(&chunk[..n]);
    }
    buf.truncate(max_bytes);
    Some(super::windows_text::decode(&buf))
}

async fn wait_for_finished(finished: &AtomicBool, bound: Duration) {
    let deadline = Instant::now() + bound;
    while !finished.load(Ordering::SeqCst) && Instant::now() < deadline {
        tokio::time::sleep(POLL_INTERVAL).await;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::util::test::set_env_var;
    use crate::workspace::test_ws;
    use tempfile::TempDir;

    /// A command that runs until something stops it — the only launch these tests can end.
    #[cfg(unix)]
    const LONG_RUNNING: &str = "sleep 30";
    #[cfg(not(unix))]
    const LONG_RUNNING: &str = "ping -n 30 127.0.0.1";

    /// What a stopped session's output file ends with: unix kills the group with a signal,
    /// Windows ends the tree and reports a plain non-zero code.
    #[cfg(unix)]
    const STOPPED_ANNOTATION: &str = "[exit status: terminated by signal]";
    #[cfg(not(unix))]
    const STOPPED_ANNOTATION: &str = "[exit status: 1]";

    async fn wait_finished(sessions: &BackgroundSessions, path: &Path, bound: Duration) -> bool {
        let deadline = Instant::now() + bound;
        loop {
            let f = sessions
                .inner
                .lock()
                .unwrap_poison()
                .get(path)
                .is_none_or(|e| e.finished.load(Ordering::SeqCst));
            if f || Instant::now() >= deadline {
                return f;
            }
            tokio::time::sleep(POLL_INTERVAL).await;
        }
    }

    fn read_file(path: &Path) -> String {
        std::fs::read_to_string(path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()))
    }

    /// The product's own output path is recognised wherever the read tool looks at it, and the
    /// near misses are not — the read tool's reading of a session's output rests on this
    /// predicate alone.
    #[test]
    fn only_the_products_own_output_path_is_recognised() {
        let temp = std::env::temp_dir();
        // A real session hands out one of these shapes.
        for name in ["bg_1a2b.out", "bg_ffff.out", "bg_0000.out"] {
            assert!(is_output_file(&temp.join(".agent").join(name)), "{name}");
        }
        for path in [
            temp.join(".agent").join("bg_ghij.out"),
            temp.join(".agent").join("bg_1a2bc.out"),
            temp.join(".agent").join("bg_1a2b.out.txt"),
            temp.join(".agent").join("spill_1a2b.txt"),
            temp.join(".agent").join("notes.out"),
            temp.join("bg_1a2b.out"),
            PathBuf::from("bg_1a2b.out"),
        ] {
            assert!(!is_output_file(&path), "{}", path.display());
        }
    }

    /// Launch `command` in the mode every background session runs in, its own text standing as the
    /// reading the platform runs.
    ///
    /// The launch runs under an owner of its own: with no agent identity every output file is
    /// recorded under the diagnostics role, which a concurrently running verification round's
    /// cleanup drains — deleting the file the test is about to read.
    async fn launch_command(
        sessions: &Arc<BackgroundSessions>,
        ws: &Path,
        command: &str,
    ) -> Result<PathBuf, String> {
        crate::agent::CURRENT_TOOL_AGENT_ID
            .scope(Some("bg_test".to_string()), async {
                sessions
                    .launch(Executed(command), Written(command), ws, ShellMode::Full)
                    .await
            })
            .await
    }

    struct LaunchExitCase {
        name: &'static str,
        command: &'static str,
        contains: &'static str,
        annotation: &'static str,
    }

    /// A launch that exits quickly is a successful launch, a legitimate non-zero exit included.
    #[tokio::test]
    async fn launch_finishes_with_its_own_status_annotation() {
        let cases = [
            LaunchExitCase {
                name: "a quick exit",
                command: "echo hello-bg",
                contains: "hello-bg",
                annotation: "[exit status: 0]",
            },
            LaunchExitCase {
                name: "a legitimate non-zero early exit",
                command: "echo legit-bg && exit 3",
                contains: "legit-bg",
                annotation: "[exit status: 3]",
            },
        ];
        for case in cases {
            let dir = TempDir::new().expect("tempdir");
            let ws = test_ws(dir.path());
            let sessions = Arc::new(BackgroundSessions::default());

            let path = launch_command(&sessions, ws.as_path(), case.command)
                .await
                .expect("launch succeeds");
            // The name this session hands out is the product's own output shape, which
            // is what makes the read tool read it as a program's output
            // ([`is_output_file`]).
            assert!(
                is_output_file(&path),
                "[{}] bg output must be the product's own output name: {}",
                case.name,
                path.display()
            );
            assert!(
                wait_finished(&sessions, &path, Duration::from_secs(10)).await,
                "[{}] the command should finish",
                case.name
            );
            let out = read_file(&path);
            assert!(out.contains(case.contains), "[{}] output: {out}", case.name);
            assert!(
                out.contains(case.annotation),
                "[{}] output: {out}",
                case.name
            );
        }
    }

    #[tokio::test]
    async fn launch_running_has_no_annotation_until_exit() {
        let dir = TempDir::new().expect("tempdir");
        let ws = test_ws(dir.path());
        let sessions = Arc::new(BackgroundSessions::default());

        let path = launch_command(&sessions, ws.as_path(), "sleep 0.7")
            .await
            .expect("launch succeeds");

        // Still running shortly after launch: no annotation, not finished.
        // The 250 ms launch probe elapses first, so the 50 ms check must land
        // before the 700 ms command exits (400 ms margin).
        tokio::time::sleep(Duration::from_millis(50)).await;
        let out = read_file(&path);
        assert!(!out.contains("[exit status:"), "output before exit: {out}");
        assert!(
            !sessions
                .inner
                .lock()
                .unwrap_poison()
                .get(&path)
                .expect("session registered")
                .finished
                .load(Ordering::SeqCst),
            "should not be finished while running"
        );

        assert!(
            wait_finished(&sessions, &path, Duration::from_secs(10)).await,
            "sleep should finish"
        );
        let out = read_file(&path);
        assert!(out.contains("[exit status: 0]"), "output: {out}");
    }

    // The 126/127 launch-failure probe is Unix-shell-specific (cmd.exe exits 1
    // for these cases); both tests are Unix-gated. Each is a synchronous launch
    // error naming the shell's own exit code, and no session or output file is
    // left behind.
    #[cfg(unix)]
    #[tokio::test]
    async fn launch_failure_command_not_found_errors() {
        let dir = TempDir::new().expect("tempdir");
        let ws = test_ws(dir.path());
        let sessions = Arc::new(BackgroundSessions::default());

        let err = launch_command(&sessions, ws.as_path(), "definitely_not_a_command_xyz_123")
            .await
            .expect_err("unknown command must be a synchronous launch error");
        assert!(
            err.contains("not found or not executable"),
            "error message: {err}"
        );
        assert!(err.contains("127"), "error should mention exit 127: {err}");
        assert!(
            sessions.inner.lock().unwrap_poison().is_empty(),
            "no session should be registered after a launch failure"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn launch_failure_not_executable_errors() {
        use std::os::unix::fs::PermissionsExt;
        let dir = TempDir::new().expect("tempdir");
        let ws = test_ws(dir.path());
        let sessions = Arc::new(BackgroundSessions::default());

        // A non-executable script invoked directly → sh exits 126.
        let script = dir.path().join("not-exec.sh");
        std::fs::write(&script, "#!/bin/sh\necho hi\n").expect("write script");
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o644)).expect("chmod");
        let err = launch_command(&sessions, ws.as_path(), "./not-exec.sh")
            .await
            .expect_err("non-executable script must be a synchronous launch error");
        assert!(
            err.contains("not found or not executable"),
            "error message: {err}"
        );
        assert!(err.contains("126"), "error should mention exit 126: {err}");
        assert!(
            sessions.inner.lock().unwrap_poison().is_empty(),
            "no session should be registered after a launch failure"
        );
    }

    #[tokio::test]
    async fn stop_kills_running_session() {
        // Grace 0: SIGTERM and SIGKILL land back-to-back — the test does not
        // need to wait out the default 5s grace.
        let _env = set_env_var("MAHBOT_BG_STOP_GRACE_SECS", Some("0"));
        let dir = TempDir::new().expect("tempdir");
        let ws = test_ws(dir.path());
        let sessions = Arc::new(BackgroundSessions::default());

        let path = launch_command(&sessions, ws.as_path(), LONG_RUNNING)
            .await
            .expect("launch succeeds");
        assert!(
            !sessions
                .inner
                .lock()
                .unwrap_poison()
                .get(&path)
                .expect("session")
                .finished
                .load(Ordering::SeqCst)
        );

        let result = sessions.stop(&path).await.expect("stop succeeds");
        assert_eq!(result, StopResult::Stopped);
        assert!(
            wait_finished(&sessions, &path, Duration::from_secs(10)).await,
            "stopped session should finish"
        );
        let out = read_file(&path);
        assert!(out.contains(STOPPED_ANNOTATION), "output: {out}");
    }

    /// Two-stage stop must not SIGKILL after the command exited during the
    /// grace: a TERM-trapping command that exits on its own within the window
    /// is a clean stop — the post-grace SIGKILL is skipped (via the re-checked
    /// `finished` flag), so there is no recycled-PGID risk and no misleading
    /// kill(-pgid) failure warning.
    #[cfg(unix)]
    #[tokio::test]
    async fn stop_grace_skips_sigkill_after_early_exit() {
        // Short grace so the test does not wait out the default 5s; long
        // enough (1s) that the 0.5s command exits well inside the window and
        // well after the 250ms launch probe.
        let _env = set_env_var("MAHBOT_BG_STOP_GRACE_SECS", Some("1"));
        let dir = TempDir::new().expect("tempdir");
        let ws = test_ws(dir.path());
        let sessions = Arc::new(BackgroundSessions::default());

        // Traps SIGTERM (ignores it), exits 0 on its own after ~0.5s.
        let path = launch_command(&sessions, ws.as_path(), "trap '' TERM; sleep 0.5; exit 0")
            .await
            .expect("launch succeeds");

        let result = sessions.stop(&path).await.expect("stop succeeds");
        assert_eq!(result, StopResult::Stopped);
        assert!(
            wait_finished(&sessions, &path, Duration::from_secs(10)).await,
            "TERM-trapping command should exit during the grace"
        );
        let out = read_file(&path);
        assert!(
            out.contains("[exit status: 0]"),
            "the command must be allowed to exit 0 during the grace, not SIGKILLed: {out}"
        );
        assert!(
            !out.contains("[exit status: terminated by signal]"),
            "the post-grace SIGKILL must be skipped once the waiter finished: {out}"
        );
    }

    #[tokio::test]
    async fn stop_already_finished_is_noop() {
        let dir = TempDir::new().expect("tempdir");
        let ws = test_ws(dir.path());
        let sessions = Arc::new(BackgroundSessions::default());

        let path = launch_command(&sessions, ws.as_path(), "echo quick")
            .await
            .expect("launch succeeds");
        assert!(
            wait_finished(&sessions, &path, Duration::from_secs(10)).await,
            "should finish"
        );
        let result = sessions.stop(&path).await.expect("stop is a no-op");
        assert_eq!(result, StopResult::AlreadyFinished);
    }

    #[tokio::test]
    async fn stop_unknown_path_errors() {
        let dir = TempDir::new().expect("tempdir");
        let sessions = Arc::new(BackgroundSessions::default());

        let err = sessions
            .stop(&dir.path().join(".agent/bg_0000.out"))
            .await
            .expect_err("unknown session must error");
        assert!(
            err.contains("No background session found"),
            "error message: {err}"
        );
    }

    #[tokio::test]
    async fn terminate_all_kills_running_sessions() {
        let dir = TempDir::new().expect("tempdir");
        let ws = test_ws(dir.path());
        let sessions = Arc::new(BackgroundSessions::default());

        let p1 = launch_command(&sessions, ws.as_path(), LONG_RUNNING)
            .await
            .expect("launch 1");
        let p2 = launch_command(&sessions, ws.as_path(), LONG_RUNNING)
            .await
            .expect("launch 2");
        assert_eq!(sessions.inner.lock().unwrap_poison().len(), 2);

        sessions.terminate_all();

        assert!(
            wait_finished(&sessions, &p1, Duration::from_secs(10)).await,
            "session 1 killed by teardown"
        );
        assert!(
            wait_finished(&sessions, &p2, Duration::from_secs(10)).await,
            "session 2 killed by teardown"
        );
        let o1 = read_file(&p1);
        assert!(o1.contains(STOPPED_ANNOTATION), "output 1: {o1}");
    }

    /// The watchdog: closing the daemon-side write end (simulating a hard
    /// daemon crash — SIGKILL/SIGSEGV leave no chance to run destructors)
    /// must make the watcher kill the whole process group.
    #[cfg(unix)]
    #[tokio::test]
    async fn watchdog_kills_group_when_write_end_closes() {
        let dir = TempDir::new().expect("tempdir");
        let ws = test_ws(dir.path());
        let sessions = Arc::new(BackgroundSessions::default());

        let path = launch_command(&sessions, ws.as_path(), "sleep 30")
            .await
            .expect("launch succeeds");

        // Take the write end out of the session entry and drop it — the
        // daemon "died". The watcher gets EOF and must SIGKILL the group.
        let write_end = sessions
            .inner
            .lock()
            .unwrap_poison()
            .get_mut(&path)
            .expect("session registered")
            .write_end
            .take()
            .expect("write end present while running");
        drop(write_end);

        assert!(
            wait_finished(&sessions, &path, Duration::from_secs(10)).await,
            "watchdog should kill the command when the daemon side dies"
        );
        let out = read_file(&path);
        assert!(
            out.contains("[exit status: terminated by signal]"),
            "output: {out}"
        );
    }

    /// A command that exits while leaving a stray grandchild in the group
    /// (`sh -c 'sleep 5 &'` — the shape of the foreground path's leftover-holding
    /// run, which a background session must NOT leave behind)
    /// must not leak the stray: the waiter closes the lifeline, the watcher
    /// SIGKILLs the group, and the stray dies with the session.
    #[cfg(unix)]
    #[tokio::test]
    async fn stray_grandchild_killed_when_command_exits() {
        let dir = TempDir::new().expect("tempdir");
        let ws = test_ws(dir.path());
        let sessions = Arc::new(BackgroundSessions::default());
        let pid_file = dir.path().join("stray.pid");
        let cmd = format!("sleep 5 & echo $! > {}", pid_file.display());

        let path = launch_command(&sessions, ws.as_path(), &cmd)
            .await
            .expect("launch succeeds — sh exits 0 even with a stray");

        assert!(
            wait_finished(&sessions, &path, Duration::from_secs(10)).await,
            "session finishes when the launched command exits"
        );
        let out = read_file(&path);
        assert!(out.contains("[exit status: 0]"), "output: {out}");

        // The stray must be dead (watcher SIGKILLed the group on lifeline EOF).
        let pid: i32 = std::fs::read_to_string(&pid_file)
            .expect("stray pid file")
            .trim()
            .parse()
            .expect("valid pid");
        let deadline = Instant::now() + Duration::from_secs(3);
        let mut alive = true;
        while Instant::now() < deadline {
            // SAFETY: kill(pid, 0) checks existence without sending a signal.
            if unsafe { libc::kill(pid, 0) } != 0 {
                alive = false;
                break;
            }
            tokio::time::sleep(POLL_INTERVAL).await;
        }
        assert!(
            !alive,
            "stray grandchild (pid={pid}) must die with the session"
        );
    }
}