aither-sandbox 0.9.1

Terminal-first command execution with heel sandboxing
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
//! Background job registry for tracking and managing background terminal tasks.
//!
//! Uses an internal command channel to avoid shared locks.

use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::PathBuf;
use std::time::Instant;

use async_channel::{Receiver, Sender};
use futures_lite::io::AsyncWriteExt;

use crate::permission::TerminalMode;

/// Information about a running or completed background job.
#[derive(Debug, Clone)]
pub struct JobInfo {
    /// Process ID.
    pub pid: u32,
    /// Stable task identifier exposed to the model.
    pub task_id: String,
    /// Stateless execution key that owns this job.
    pub execution_key: String,
    /// The script that was executed.
    pub script: String,
    /// The permission mode used.
    pub mode: TerminalMode,
    /// When the job was started.
    pub started_at: Instant,
    /// Current status of the job.
    pub status: JobStatus,
    /// Path to output file.
    pub output_path: Option<PathBuf>,
}

/// Status of a background job.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JobStatus {
    /// Job is currently running.
    Running,
    /// Job completed successfully.
    Completed {
        /// Exit code of the process.
        exit_code: i32,
    },
    /// Job failed with an error.
    Failed {
        /// Error message.
        error: String,
    },
    /// Job was killed by user.
    Killed,
}

/// Incremental read result for a background terminal buffer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TerminalDelta {
    /// Stable task identifier exposed to the model.
    pub task_id: String,
    /// Cursor the caller should pass on the next read.
    pub cursor: usize,
    /// Total bytes currently buffered for this task.
    pub total_bytes: usize,
    /// Newly read bytes from the terminal buffer.
    pub bytes: Vec<u8>,
    /// Current task status at the time of the read.
    pub status: JobStatus,
}

/// Sender used by the registry to push bytes into a running process stdin.
pub type TerminalInputSender = Sender<Vec<u8>>;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TerminalStream {
    Stdout,
    Stderr,
}

#[derive(Debug)]
struct JobState {
    info: JobInfo,
    terminal_buffer: Vec<u8>,
    stdout_buffer: Vec<u8>,
    stderr_buffer: Vec<u8>,
    stdout_closed: bool,
    stderr_closed: bool,
    input_tx: Option<TerminalInputSender>,
    kill_switch: Option<Sender<()>>,
    output_redirect: Option<async_fs::File>,
    finished_at: Option<Instant>,
}

enum JobCommand {
    Register {
        pid: u32,
        task_id: String,
        execution_key: String,
        script: String,
        mode: TerminalMode,
        output_path: Option<PathBuf>,
    },
    AttachTerminalInput {
        pid: u32,
        input_tx: TerminalInputSender,
    },
    AttachKillSwitch {
        pid: u32,
        kill_tx: Sender<()>,
    },
    AppendTerminalOutput {
        pid: u32,
        stream: TerminalStream,
        chunk: Vec<u8>,
    },
    CloseTerminalStream {
        pid: u32,
        stream: TerminalStream,
    },
    Complete {
        pid: u32,
        exit_code: i32,
        output_path: Option<PathBuf>,
    },
    Fail {
        pid: u32,
        error: String,
        output_path: Option<PathBuf>,
    },
    List {
        reply: Sender<Vec<JobInfo>>,
    },
    Get {
        pid: u32,
        reply: Sender<Option<JobInfo>>,
    },
    Kill {
        pid: u32,
        reply: Sender<bool>,
    },
    KillByTaskId {
        task_id: String,
        reply: Sender<bool>,
    },
    KillByExecutionKey {
        execution_key: String,
        reply: Sender<usize>,
    },
    InputTerminal {
        task_id: String,
        bytes: Vec<u8>,
        reply: Sender<Result<(), String>>,
    },
    StartOutputRedirect {
        task_id: String,
        output_path: PathBuf,
        reply: Sender<Result<Vec<u8>, String>>,
    },
    TerminalOutput {
        pid: u32,
        reply: Sender<Option<(Vec<u8>, Vec<u8>)>>,
    },
    ReadTerminalDelta {
        task_id: String,
        cursor: usize,
        max_bytes: usize,
        reply: Sender<Result<TerminalDelta, String>>,
    },
    TerminalStreamsClosed {
        pid: u32,
        reply: Sender<bool>,
    },
    FormatRunning {
        reply: Sender<String>,
    },
    HasRunning {
        reply: Sender<bool>,
    },
}

/// Registry handle for tracking background jobs.
///
/// Cloning keeps a sender to the same registry service.
#[derive(Clone, Debug)]
pub struct JobRegistry {
    tx: Sender<JobCommand>,
}

/// Background service that owns the job registry state.
#[derive(Debug)]
pub struct JobRegistryService {
    rx: Receiver<JobCommand>,
}

/// Creates a registry handle and its background service.
#[must_use]
pub fn job_registry_channel() -> (JobRegistry, JobRegistryService) {
    let (tx, rx) = async_channel::unbounded();
    (JobRegistry { tx }, JobRegistryService { rx })
}

impl JobRegistry {
    async fn send_command(&self, command: JobCommand) {
        self.tx
            .send(command)
            .await
            .expect("job registry service unavailable");
    }

    async fn recv_reply<T>(reply_rx: Receiver<T>) -> T {
        reply_rx
            .recv()
            .await
            .expect("job registry response dropped")
    }

    /// Registers a new running job.
    pub async fn register(
        &self,
        pid: u32,
        task_id: &str,
        execution_key: &str,
        script: &str,
        mode: TerminalMode,
        output_path: Option<PathBuf>,
    ) {
        self.send_command(JobCommand::Register {
            pid,
            task_id: task_id.to_string(),
            execution_key: execution_key.to_string(),
            script: script.to_string(),
            mode,
            output_path,
        })
        .await;
    }

    /// Attaches a stdin input channel to a running job.
    pub async fn attach_terminal_input(&self, pid: u32, input_tx: TerminalInputSender) {
        self.send_command(JobCommand::AttachTerminalInput { pid, input_tx })
            .await;
    }

    /// Attaches a kill switch used by runtimes without host-visible PIDs.
    pub async fn attach_kill_switch(&self, pid: u32, kill_tx: Sender<()>) {
        self.send_command(JobCommand::AttachKillSwitch { pid, kill_tx })
            .await;
    }

    /// Appends stdout bytes for a running job.
    pub async fn append_stdout(&self, pid: u32, chunk: Vec<u8>) {
        self.send_command(JobCommand::AppendTerminalOutput {
            pid,
            stream: TerminalStream::Stdout,
            chunk,
        })
        .await;
    }

    /// Appends stderr bytes for a running job.
    pub async fn append_stderr(&self, pid: u32, chunk: Vec<u8>) {
        self.send_command(JobCommand::AppendTerminalOutput {
            pid,
            stream: TerminalStream::Stderr,
            chunk,
        })
        .await;
    }

    /// Marks stdout stream closed.
    pub async fn close_stdout(&self, pid: u32) {
        self.send_command(JobCommand::CloseTerminalStream {
            pid,
            stream: TerminalStream::Stdout,
        })
        .await;
    }

    /// Marks stderr stream closed.
    pub async fn close_stderr(&self, pid: u32) {
        self.send_command(JobCommand::CloseTerminalStream {
            pid,
            stream: TerminalStream::Stderr,
        })
        .await;
    }

    /// Sends bytes to a running task terminal stdin.
    ///
    /// # Errors
    /// Returns an error when the task does not exist or no stdin channel is attached.
    pub async fn terminal_input(&self, task_id: &str, bytes: Vec<u8>) -> Result<(), String> {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobCommand::InputTerminal {
            task_id: task_id.to_string(),
            bytes,
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Starts continuous output redirection for a task and returns current snapshot bytes.
    ///
    /// # Errors
    /// Returns an error when the task does not exist or output cannot be redirected.
    pub async fn start_output_redirect(
        &self,
        task_id: &str,
        output_path: PathBuf,
    ) -> Result<Vec<u8>, String> {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobCommand::StartOutputRedirect {
            task_id: task_id.to_string(),
            output_path,
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Returns true when both stdout/stderr streams are closed for the PID.
    pub async fn terminal_streams_closed(&self, pid: u32) -> bool {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobCommand::TerminalStreamsClosed {
            pid,
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Returns collected stdout/stderr buffers for a PID.
    pub async fn terminal_output(&self, pid: u32) -> Option<(Vec<u8>, Vec<u8>)> {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobCommand::TerminalOutput {
            pid,
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Returns terminal output added since the provided cursor.
    ///
    /// # Errors
    /// Returns an error when the task id is unknown.
    pub async fn terminal_read(
        &self,
        task_id: &str,
        cursor: usize,
        max_bytes: usize,
    ) -> Result<TerminalDelta, String> {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobCommand::ReadTerminalDelta {
            task_id: task_id.to_string(),
            cursor,
            max_bytes,
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Marks a job as completed.
    pub async fn complete(&self, pid: u32, exit_code: i32, output_path: Option<PathBuf>) {
        self.send_command(JobCommand::Complete {
            pid,
            exit_code,
            output_path,
        })
        .await;
    }

    /// Marks a job as failed.
    pub async fn fail(&self, pid: u32, error: &str, output_path: Option<PathBuf>) {
        self.send_command(JobCommand::Fail {
            pid,
            error: error.to_string(),
            output_path,
        })
        .await;
    }

    /// Lists all jobs.
    pub async fn list(&self) -> Vec<JobInfo> {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobCommand::List { reply: reply_tx })
            .await;
        Self::recv_reply(reply_rx).await
    }

    /// Gets information about a specific job by PID.
    pub async fn get(&self, pid: u32) -> Option<JobInfo> {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobCommand::Get {
            pid,
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Kills a running job by its PID.
    pub async fn kill(&self, pid: u32) -> bool {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobCommand::Kill {
            pid,
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Kills a running job by its task ID.
    pub async fn kill_by_task_id(&self, task_id: &str) -> bool {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobCommand::KillByTaskId {
            task_id: task_id.to_string(),
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Kills every job that is still running in this registry.
    pub async fn kill_running(&self) -> usize {
        let running_pids = self
            .list()
            .await
            .into_iter()
            .filter(|job| job.status == JobStatus::Running)
            .map(|job| job.pid)
            .collect::<Vec<_>>();
        let mut killed = 0;
        for pid in running_pids {
            killed += usize::from(self.kill(pid).await);
        }
        killed
    }

    /// Kills all running jobs owned by an execution key.
    pub async fn kill_by_execution_key(&self, execution_key: &str) -> usize {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobCommand::KillByExecutionKey {
            execution_key: execution_key.to_string(),
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Blocking variant of `kill_by_execution_key`, intended for drop-time cleanup.
    #[must_use]
    pub fn kill_by_execution_key_blocking(&self, execution_key: &str) -> usize {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        if self
            .tx
            .send_blocking(JobCommand::KillByExecutionKey {
                execution_key: execution_key.to_string(),
                reply: reply_tx,
            })
            .is_err()
        {
            return 0;
        }
        reply_rx.recv_blocking().unwrap_or(0)
    }

    /// Formats only RUNNING jobs for compression preservation.
    pub async fn format_running_jobs(&self) -> String {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobCommand::FormatRunning { reply: reply_tx })
            .await;
        Self::recv_reply(reply_rx).await
    }

    /// Returns true if there are any running jobs.
    pub async fn has_running(&self) -> bool {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobCommand::HasRunning { reply: reply_tx })
            .await;
        Self::recv_reply(reply_rx).await
    }
}

impl JobRegistryService {
    /// Runs the registry service loop until all senders are dropped.
    pub async fn serve(self) {
        let mut jobs: HashMap<u32, JobState> = HashMap::new();

        while let Ok(cmd) = self.rx.recv().await {
            handle_job_command(&mut jobs, cmd).await;
        }
    }
}

async fn handle_job_command(jobs: &mut HashMap<u32, JobState>, cmd: JobCommand) {
    match cmd {
        JobCommand::Register {
            pid,
            task_id,
            execution_key,
            script,
            mode,
            output_path,
        } => register_job(jobs, pid, task_id, execution_key, script, mode, output_path),
        JobCommand::AttachTerminalInput { pid, input_tx } => {
            if let Some(job) = jobs.get_mut(&pid) {
                job.input_tx = Some(input_tx);
            }
        }
        JobCommand::AttachKillSwitch { pid, kill_tx } => {
            if let Some(job) = jobs.get_mut(&pid) {
                job.kill_switch = Some(kill_tx);
            }
        }
        JobCommand::AppendTerminalOutput { pid, stream, chunk } => {
            append_terminal_output(jobs, pid, stream, chunk).await;
        }
        JobCommand::CloseTerminalStream { pid, stream } => close_terminal_stream(jobs, pid, stream),
        JobCommand::Complete {
            pid,
            exit_code,
            output_path,
        } => complete_job(jobs, pid, exit_code, output_path).await,
        JobCommand::Fail {
            pid,
            error,
            output_path,
        } => fail_job(jobs, pid, error, output_path).await,
        JobCommand::List { reply } => {
            let items = jobs.values().map(|state| state.info.clone()).collect();
            let _ = reply.send(items).await;
        }
        JobCommand::Get { pid, reply } => {
            let item = jobs.get(&pid).map(|state| state.info.clone());
            let _ = reply.send(item).await;
        }
        JobCommand::Kill { pid, reply } => {
            let result = kill_job(jobs, pid).await;
            let _ = reply.send(result).await;
        }
        JobCommand::KillByTaskId { task_id, reply } => {
            let result = kill_by_task_id(jobs, &task_id).await;
            let _ = reply.send(result).await;
        }
        JobCommand::KillByExecutionKey {
            execution_key,
            reply,
        } => {
            let killed = kill_by_execution_key(jobs, &execution_key).await;
            let _ = reply.send(killed).await;
        }
        JobCommand::InputTerminal {
            task_id,
            bytes,
            reply,
        } => {
            let result = input_terminal(jobs, &task_id, bytes).await;
            let _ = reply.send(result).await;
        }
        JobCommand::StartOutputRedirect {
            task_id,
            output_path,
            reply,
        } => {
            let result = redirect_task_output(jobs, &task_id, output_path).await;
            let _ = reply.send(result).await;
        }
        JobCommand::TerminalOutput { pid, reply } => {
            send_terminal_output(jobs, pid, reply).await;
        }
        JobCommand::ReadTerminalDelta {
            task_id,
            cursor,
            max_bytes,
            reply,
        } => {
            let result = read_terminal_delta(jobs, &task_id, cursor, max_bytes);
            let _ = reply.send(result).await;
        }
        JobCommand::TerminalStreamsClosed { pid, reply } => {
            let closed = jobs
                .get(&pid)
                .is_some_and(|job| job.stdout_closed && job.stderr_closed);
            let _ = reply.send(closed).await;
        }
        JobCommand::FormatRunning { reply } => {
            let _ = reply.send(format_running_jobs(jobs)).await;
        }
        JobCommand::HasRunning { reply } => {
            let _ = reply.send(has_running_job(jobs)).await;
        }
    }
}

async fn send_terminal_output(
    jobs: &HashMap<u32, JobState>,
    pid: u32,
    reply: Sender<Option<(Vec<u8>, Vec<u8>)>>,
) {
    let output = jobs
        .get(&pid)
        .map(|job| (job.stdout_buffer.clone(), job.stderr_buffer.clone()));
    let _ = reply.send(output).await;
}

fn has_running_job(jobs: &HashMap<u32, JobState>) -> bool {
    jobs.values()
        .any(|job| matches!(job.info.status, JobStatus::Running))
}

fn register_job(
    jobs: &mut HashMap<u32, JobState>,
    pid: u32,
    task_id: String,
    execution_key: String,
    script: String,
    mode: TerminalMode,
    output_path: Option<PathBuf>,
) {
    let info = JobInfo {
        pid,
        task_id,
        execution_key,
        script,
        mode,
        started_at: Instant::now(),
        status: JobStatus::Running,
        output_path,
    };
    jobs.insert(pid, JobState::new(info));
    tracing::debug!(pid = %pid, "registered background job");
}

impl JobState {
    const fn new(info: JobInfo) -> Self {
        Self {
            info,
            terminal_buffer: Vec::new(),
            stdout_buffer: Vec::new(),
            stderr_buffer: Vec::new(),
            stdout_closed: false,
            stderr_closed: false,
            input_tx: None,
            kill_switch: None,
            output_redirect: None,
            finished_at: None,
        }
    }
}

async fn append_terminal_output(
    jobs: &mut HashMap<u32, JobState>,
    pid: u32,
    stream: TerminalStream,
    chunk: Vec<u8>,
) {
    if chunk.is_empty() {
        return;
    }
    if let Some(job) = jobs.get_mut(&pid) {
        job.terminal_buffer.extend_from_slice(&chunk);
        if let Some(file) = job.output_redirect.as_mut()
            && let Err(error) = file.write_all(&chunk).await
        {
            mark_job_failed(
                job,
                format!(
                    "failed to append redirected output for task {}: {error}",
                    job.info.task_id
                ),
            );
            tracing::error!(
                pid = %pid,
                error = %error,
                "failed to append redirected output"
            );
        }
        match stream {
            TerminalStream::Stdout => job.stdout_buffer.extend_from_slice(&chunk),
            TerminalStream::Stderr => job.stderr_buffer.extend_from_slice(&chunk),
        }
    }
}

fn close_terminal_stream(jobs: &mut HashMap<u32, JobState>, pid: u32, stream: TerminalStream) {
    if let Some(job) = jobs.get_mut(&pid) {
        match stream {
            TerminalStream::Stdout => job.stdout_closed = true,
            TerminalStream::Stderr => job.stderr_closed = true,
        }
    }
}

async fn complete_job(
    jobs: &mut HashMap<u32, JobState>,
    pid: u32,
    exit_code: i32,
    output_path: Option<PathBuf>,
) {
    if let Some(job) = jobs.get_mut(&pid) {
        if !matches!(job.info.status, JobStatus::Running) {
            tracing::debug!(
                pid = %pid,
                status = ?job.info.status,
                "ignoring complete for non-running job"
            );
            return;
        }
        if let Err(error) = finalize_output_redirect(job).await {
            tracing::error!(
                pid = %pid,
                error = %error,
                "failed to flush redirected output on complete"
            );
            mark_job_failed(job, error);
            return;
        }
        job.info.status = JobStatus::Completed { exit_code };
        job.finished_at = Some(Instant::now());
        job.kill_switch = None;
        if output_path.is_some() {
            job.info.output_path = output_path;
        }
        tracing::debug!(pid = %pid, exit_code = %exit_code, "job completed");
    }
}

async fn fail_job(
    jobs: &mut HashMap<u32, JobState>,
    pid: u32,
    error: String,
    output_path: Option<PathBuf>,
) {
    if let Some(job) = jobs.get_mut(&pid) {
        if !matches!(job.info.status, JobStatus::Running) {
            tracing::debug!(
                pid = %pid,
                status = ?job.info.status,
                "ignoring fail for non-running job"
            );
            return;
        }
        let status_error = if let Err(finalize_error) = finalize_output_redirect(job).await {
            format!("{error}; additionally failed to flush redirected output: {finalize_error}")
        } else {
            error
        };
        mark_job_failed(job, status_error);
        job.kill_switch = None;
        if output_path.is_some() {
            job.info.output_path = output_path;
        }
        tracing::debug!(pid = %pid, "job failed");
    }
}

async fn kill_by_task_id(jobs: &mut HashMap<u32, JobState>, task_id: &str) -> bool {
    if let Some(pid) = find_pid_by_task_id(jobs, task_id) {
        kill_job(jobs, pid).await
    } else {
        false
    }
}

async fn kill_by_execution_key(jobs: &mut HashMap<u32, JobState>, execution_key: &str) -> usize {
    let pids: Vec<u32> = jobs
        .iter()
        .filter_map(|(pid, state)| {
            (state.info.execution_key == execution_key
                && matches!(state.info.status, JobStatus::Running))
            .then_some(*pid)
        })
        .collect();

    let mut killed = 0usize;
    for pid in pids {
        if kill_job(jobs, pid).await {
            killed += 1;
        }
    }
    killed
}

async fn input_terminal(
    jobs: &HashMap<u32, JobState>,
    task_id: &str,
    bytes: Vec<u8>,
) -> Result<(), String> {
    let Some(pid) = find_pid_by_task_id(jobs, task_id) else {
        return Err(format!("unknown task_id: {task_id}"));
    };
    let Some(job) = jobs.get(&pid) else {
        return Err(format!("unknown task_id: {task_id}"));
    };
    if !matches!(job.info.status, JobStatus::Running) {
        return Err(format!(
            "task {} is not running; current status: {:?}",
            task_id, job.info.status
        ));
    }
    let Some(tx) = &job.input_tx else {
        return Err(format!(
            "task {task_id} does not support terminal input in this runtime"
        ));
    };
    tx.send(bytes)
        .await
        .map_err(|_| format!("terminal input channel closed for task {task_id}"))
}

async fn redirect_task_output(
    jobs: &mut HashMap<u32, JobState>,
    task_id: &str,
    output_path: PathBuf,
) -> Result<Vec<u8>, String> {
    let Some(pid) = find_pid_by_task_id(jobs, task_id) else {
        return Err(format!("unknown task_id: {task_id}"));
    };
    let Some(job) = jobs.get_mut(&pid) else {
        return Err(format!("unknown task_id: {task_id}"));
    };
    start_output_redirect(job, output_path).await
}

fn read_terminal_delta(
    jobs: &HashMap<u32, JobState>,
    task_id: &str,
    cursor: usize,
    max_bytes: usize,
) -> Result<TerminalDelta, String> {
    find_pid_by_task_id(jobs, task_id).map_or_else(
        || Err(format!("unknown task_id: {task_id}")),
        |pid| {
            jobs.get(&pid).map_or_else(
                || Err(format!("unknown task_id: {task_id}")),
                |job| terminal_read(job, cursor, max_bytes),
            )
        },
    )
}

async fn start_output_redirect(
    job: &mut JobState,
    output_path: PathBuf,
) -> Result<Vec<u8>, String> {
    if let Some(existing) = job.info.output_path.as_ref() {
        if existing != &output_path {
            return Err(format!(
                "task {} already redirects output to {}",
                job.info.task_id,
                existing.display()
            ));
        }
        return Ok(job.terminal_buffer.clone());
    }

    let mut file = async_fs::OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .open(&output_path)
        .await
        .map_err(|error| {
            format!(
                "failed to open output redirect file {}: {error}",
                output_path.display()
            )
        })?;

    file.write_all(&job.terminal_buffer)
        .await
        .map_err(|error| {
            format!(
                "failed to write initial output redirect snapshot for task {}: {error}",
                job.info.task_id
            )
        })?;
    file.flush().await.map_err(|error| {
        format!(
            "failed to flush initial output redirect snapshot for task {}: {error}",
            job.info.task_id
        )
    })?;

    job.info.output_path = Some(output_path);
    job.output_redirect = Some(file);
    Ok(job.terminal_buffer.clone())
}

fn mark_job_failed(job: &mut JobState, error: String) {
    job.info.status = JobStatus::Failed { error };
    job.finished_at = Some(Instant::now());
    job.kill_switch = None;
}

async fn finalize_output_redirect(job: &mut JobState) -> Result<(), String> {
    if let Some(mut file) = job.output_redirect.take()
        && let Err(error) = file.flush().await
    {
        return Err(format!(
            "failed to flush redirected output for task {}: {error}",
            job.info.task_id
        ));
    }
    Ok(())
}

fn find_pid_by_task_id(jobs: &HashMap<u32, JobState>, task_id: &str) -> Option<u32> {
    jobs.iter().find_map(|(pid, state)| {
        if state.info.task_id == task_id {
            Some(*pid)
        } else {
            None
        }
    })
}

async fn kill_job(jobs: &mut HashMap<u32, JobState>, pid: u32) -> bool {
    if let Some(job) = jobs.get_mut(&pid) {
        if !matches!(job.info.status, JobStatus::Running) {
            tracing::warn!(pid = %pid, "cannot kill non-running job");
            return false;
        }

        if let Some(kill_switch) = job.kill_switch.take() {
            if kill_switch.send(()).await.is_err() {
                tracing::warn!(pid = %pid, "failed to signal runtime kill switch");
                return false;
            }
            if let Err(error) = finalize_output_redirect(job).await {
                tracing::warn!(
                    pid = %pid,
                    error = %error,
                    "failed to flush redirected output after kill switch signal"
                );
            }
            job.info.status = JobStatus::Killed;
            job.finished_at = Some(Instant::now());
            job.stdout_closed = true;
            job.stderr_closed = true;
            tracing::info!(pid = %pid, "killed job via runtime kill switch");
            return true;
        }

        #[cfg(unix)]
        {
            let result = unsafe { libc::kill(-pid.cast_signed(), libc::SIGKILL) };
            if result == 0 {
                if let Err(error) = finalize_output_redirect(job).await {
                    tracing::warn!(
                        pid = %pid,
                        error = %error,
                        "failed to flush redirected output after kill"
                    );
                }
                job.info.status = JobStatus::Killed;
                job.finished_at = Some(Instant::now());
                job.stdout_closed = true;
                job.stderr_closed = true;
                tracing::info!(pid = %pid, "killed job");
                return true;
            }
            let error = std::io::Error::last_os_error();
            tracing::warn!(pid = %pid, error = %error, "failed to kill job");
            return false;
        }

        #[cfg(windows)]
        {
            let output = async_process::Command::new("taskkill")
                .args(["/F", "/T", "/PID", &pid.to_string()])
                .output()
                .await;
            match output {
                Ok(output) if output.status.success() => {
                    if let Err(error) = finalize_output_redirect(job).await {
                        tracing::warn!(
                            pid = %pid,
                            error = %error,
                            "failed to flush redirected output after kill"
                        );
                    }
                    job.info.status = JobStatus::Killed;
                    job.finished_at = Some(Instant::now());
                    job.stdout_closed = true;
                    job.stderr_closed = true;
                    tracing::info!(pid = %pid, "killed job (Windows)");
                    return true;
                }
                Ok(output) => {
                    tracing::warn!(
                        pid = %pid,
                        status = %output.status,
                        stderr = %String::from_utf8_lossy(&output.stderr),
                        "taskkill reported failure"
                    );
                    return false;
                }
                Err(err) => {
                    tracing::warn!(pid = %pid, error = %err, "failed to kill job (Windows)");
                    return false;
                }
            }
        }
    }

    false
}

fn format_running_jobs(jobs: &HashMap<u32, JobState>) -> String {
    let running: Vec<_> = jobs
        .values()
        .filter(|job| matches!(job.info.status, JobStatus::Running))
        .collect();

    if running.is_empty() {
        return String::new();
    }

    let mut output = String::new();
    for job in running {
        let script_preview = if job.info.script.len() > 50 {
            format!("{}...", &job.info.script[..50])
        } else {
            job.info.script.clone()
        };

        let output_path = job
            .info
            .output_path
            .as_ref()
            .map_or_else(|| "(no output)".to_string(), |p| p.display().to_string());

        let _ = writeln!(
            output,
            "  - task {} (pid {}): `{}` -> {}",
            job.info.task_id, job.info.pid, script_preview, output_path
        );
    }

    output
}

fn terminal_read(job: &JobState, cursor: usize, max_bytes: usize) -> Result<TerminalDelta, String> {
    let total_bytes = job.terminal_buffer.len();
    if cursor > total_bytes {
        return Err(format!(
            "cursor {cursor} exceeds terminal buffer size {total_bytes} for task {}",
            job.info.task_id
        ));
    }
    let end = total_bytes.min(cursor.saturating_add(max_bytes));
    Ok(TerminalDelta {
        task_id: job.info.task_id.clone(),
        cursor: end,
        total_bytes,
        bytes: job.terminal_buffer[cursor..end].to_vec(),
        status: job.info.status.clone(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use executor_core::Executor;
    use executor_core::Task;
    use executor_core::tokio::TokioGlobal;
    use tempfile::tempdir;

    #[tokio::test]
    async fn test_job_registry_lifecycle() {
        let (registry, service) = job_registry_channel();
        TokioGlobal
            .spawn(async move { service.serve().await })
            .detach();

        registry
            .register(
                12345,
                "amber-forest-thunder-pearl",
                "exec-test",
                "sleep 10",
                TerminalMode::Sandboxed,
                Some(PathBuf::from("outputs/12345.txt")),
            )
            .await;

        let jobs = registry.list().await;
        assert_eq!(jobs.len(), 1);
        assert_eq!(jobs[0].pid, 12345);
        assert_eq!(jobs[0].task_id, "amber-forest-thunder-pearl");
        assert_eq!(jobs[0].execution_key, "exec-test");
        assert!(matches!(jobs[0].status, JobStatus::Running));

        registry.complete(12345, 0, None).await;
        let job = registry.get(12345).await.unwrap();
        assert!(matches!(job.status, JobStatus::Completed { exit_code: 0 }));
    }

    #[tokio::test]
    async fn test_format_running_jobs() {
        let (registry, service) = job_registry_channel();
        TokioGlobal
            .spawn(async move { service.serve().await })
            .detach();

        registry
            .register(
                1,
                "task-a",
                "exec-a",
                "echo hello",
                TerminalMode::Sandboxed,
                None,
            )
            .await;
        registry
            .register(
                2,
                "task-b",
                "exec-b",
                "sleep 5",
                TerminalMode::Sandboxed,
                None,
            )
            .await;
        registry.complete(2, 0, None).await;

        let running = registry.format_running_jobs().await;
        assert!(running.contains("task task-a"));
        assert!(!running.contains("task task-b"));
    }

    #[tokio::test]
    async fn test_output_redirect_streams_full_output() {
        let (registry, service) = job_registry_channel();
        TokioGlobal
            .spawn(async move { service.serve().await })
            .detach();

        let temp = tempdir().unwrap();
        let redirect_path = temp.path().join("task-stream.log");

        registry
            .register(
                101,
                "task-stream",
                "exec-stream",
                "printf one",
                TerminalMode::Sandboxed,
                None,
            )
            .await;

        registry
            .append_stdout(101, b"line1\nline2\n".to_vec())
            .await;
        let snapshot = registry
            .start_output_redirect("task-stream", redirect_path.clone())
            .await
            .unwrap();
        assert_eq!(String::from_utf8_lossy(&snapshot), "line1\nline2\n");

        registry.append_stderr(101, b"line3\n".to_vec()).await;
        registry.complete(101, 0, None).await;
        let job = registry.get(101).await.unwrap();
        assert!(matches!(job.status, JobStatus::Completed { exit_code: 0 }));

        let redirected = async_fs::read(&redirect_path).await.unwrap();
        assert_eq!(
            String::from_utf8_lossy(&redirected),
            "line1\nline2\nline3\n"
        );
    }

    #[tokio::test]
    async fn test_read_terminal_delta_reads_incrementally() {
        let (registry, service) = job_registry_channel();
        TokioGlobal
            .spawn(async move { service.serve().await })
            .detach();

        registry
            .register(
                202,
                "task-delta",
                "exec-delta",
                "tail -f log",
                TerminalMode::Sandboxed,
                None,
            )
            .await;
        registry.append_stdout(202, b"hello ".to_vec()).await;
        registry.append_stderr(202, b"world".to_vec()).await;

        let first = registry.terminal_read("task-delta", 0, 6).await.unwrap();
        assert_eq!(String::from_utf8_lossy(&first.bytes), "hello ");
        assert_eq!(first.cursor, 6);
        assert_eq!(first.total_bytes, 11);
        assert!(matches!(first.status, JobStatus::Running));

        let second = registry
            .terminal_read("task-delta", first.cursor, 32)
            .await
            .unwrap();
        assert_eq!(String::from_utf8_lossy(&second.bytes), "world");
        assert_eq!(second.cursor, 11);
        assert_eq!(second.total_bytes, 11);
    }

    #[tokio::test]
    async fn test_kill_by_execution_key_no_match() {
        let (registry, service) = job_registry_channel();
        TokioGlobal
            .spawn(async move { service.serve().await })
            .detach();

        registry
            .register(
                1,
                "task-a",
                "exec-a",
                "echo hello",
                TerminalMode::Sandboxed,
                None,
            )
            .await;
        registry.complete(1, 0, None).await;

        let killed = registry.kill_by_execution_key("exec-b").await;
        assert_eq!(killed, 0);
    }

    #[tokio::test]
    async fn test_kill_switch_path_marks_job_killed() {
        let (registry, service) = job_registry_channel();
        TokioGlobal
            .spawn(async move { service.serve().await })
            .detach();

        registry
            .register(
                555,
                "task-kill-switch",
                "exec-kill-switch",
                "sleep 10",
                TerminalMode::Sandboxed,
                None,
            )
            .await;
        let (kill_tx, kill_rx) = async_channel::bounded::<()>(1);
        registry.attach_kill_switch(555, kill_tx).await;

        assert!(registry.kill_by_task_id("task-kill-switch").await);
        assert!(kill_rx.recv().await.is_ok());
        let job = registry.get(555).await.expect("job should exist");
        assert!(matches!(job.status, JobStatus::Killed));
    }

    #[tokio::test]
    async fn test_complete_does_not_override_killed_status() {
        let (registry, service) = job_registry_channel();
        TokioGlobal
            .spawn(async move { service.serve().await })
            .detach();

        registry
            .register(
                556,
                "task-killed-complete",
                "exec-killed-complete",
                "sleep 10",
                TerminalMode::Sandboxed,
                None,
            )
            .await;
        let (kill_tx, _kill_rx) = async_channel::bounded::<()>(1);
        registry.attach_kill_switch(556, kill_tx).await;
        assert!(registry.kill_by_task_id("task-killed-complete").await);

        registry.complete(556, 0, None).await;
        let job = registry.get(556).await.expect("job should exist");
        assert!(matches!(job.status, JobStatus::Killed));
    }
}