aither-sandbox 0.16.0

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
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
//! 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;
use crate::process_tree::{JobMarker, JobTree, KillTreeError, ProcessScanner};

/// 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>,
    /// Complete lines only, each from one stream, in the order they
    /// completed: what the `monitor` pump reads.
    line_buffer: Vec<u8>,
    stdout_partial: Vec<u8>,
    stderr_partial: Vec<u8>,
    stdout_buffer: Vec<u8>,
    stderr_buffer: Vec<u8>,
    stdout_closed: bool,
    stderr_closed: bool,
    input_tx: Option<TerminalInputSender>,
    kill_switch: Option<Sender<()>>,
    process_tree: Option<JobTree>,
    /// How many kills of the job run outside the registry; an ending the
    /// job's own flow reports meanwhile waits in `deferred_end`.
    kills_in_flight: usize,
    deferred_end: Option<Ending>,
    /// Callers of `get_by_task_id_settled` parked until the last kill in
    /// flight records its outcome.
    settled_waiters: Vec<Sender<Option<JobInfo>>>,
    output_redirect: Option<async_fs::File>,
    finished_at: Option<Instant>,
}

/// State mutations sent to the registry service; none expect a reply.
enum StateCommand {
    Register {
        pid: u32,
        task_id: String,
        execution_key: String,
        script: String,
        mode: TerminalMode,
        output_path: Option<PathBuf>,
        process_tree: Option<JobTree>,
    },
    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>,
    },
    RecordFileReads {
        reads: Vec<(PathBuf, FileFingerprint)>,
    },
}

/// Registry queries and job-control requests, each answered on `reply`.
enum JobRequest {
    List {
        reply: Sender<Vec<JobInfo>>,
    },
    Get {
        pid: u32,
        reply: Sender<Option<JobInfo>>,
    },
    GetByTaskId {
        task_id: String,
        reply: Sender<Option<JobInfo>>,
    },
    GetByTaskIdSettled {
        task_id: String,
        reply: Sender<Option<JobInfo>>,
    },
    BeginKill {
        pid: u32,
        reply: Sender<KillPlan>,
    },
    BeginKillByTaskId {
        task_id: String,
        reply: Sender<Option<(u32, KillPlan)>>,
    },
    BeginKillByExecutionKey {
        execution_key: String,
        reply: Sender<Vec<(u32, KillPlan)>>,
    },
    EndKill {
        pid: u32,
        killed: bool,
        reply: Sender<bool>,
    },
    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,
        /// Whether this read is a model read of the merged terminal buffer,
        /// tracked by the unchanged-read refusal; a monitor pump's reads are
        /// not, and read the complete-line buffer instead.
        tracked: bool,
        reply: Sender<Result<TerminalDelta, String>>,
    },
    FileReadsUnchanged {
        reads: Vec<(PathBuf, FileFingerprint)>,
        reply: Sender<bool>,
    },
    TerminalStreamsClosed {
        pid: u32,
        reply: Sender<bool>,
    },
    FormatRunning {
        reply: Sender<String>,
    },
    HasRunning {
        reply: Sender<bool>,
    },
}

/// A file's `(len, modified)` stamp a script read returned with: two reads
/// whose fingerprints match deliver the same bytes.
pub type FileFingerprint = (u64, Option<std::time::SystemTime>);

/// How the registry's caller kills a job: the kill itself runs outside the
/// registry's state actor, which would otherwise stall every other job's
/// output, listing and kills meanwhile.
enum KillPlan {
    /// The registry decided at once.
    Done(bool),
    /// Kill the job's whole process tree.
    Tree(JobTree),
    /// Kill the process group led by this pid.
    Group(u32),
}

/// How a job's own flow ended it while a kill of it was running.
#[derive(Debug)]
enum Ending {
    Complete {
        exit_code: i32,
        output_path: Option<PathBuf>,
    },
    Fail {
        error: String,
        output_path: Option<PathBuf>,
    },
}

/// Message delivered to the registry service.
enum JobCommand {
    State(StateCommand),
    Request(JobRequest),
}

impl From<StateCommand> for JobCommand {
    fn from(command: StateCommand) -> Self {
        Self::State(command)
    }
}

impl From<JobRequest> for JobCommand {
    fn from(request: JobRequest) -> Self {
        Self::Request(request)
    }
}

/// Registry handle for tracking background jobs.
///
/// Cloning keeps a sender to the same registry service.
#[derive(Clone, Debug)]
pub struct JobRegistry {
    tx: Sender<JobCommand>,
    /// The tree scanner — kept for the other unixes and the tests; on Linux
    /// the supervisor owns each tree.
    #[cfg_attr(target_os = "linux", allow(dead_code))]
    scanner: ProcessScanner,
}

/// 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,
            scanner: ProcessScanner::default(),
        },
        JobRegistryService { rx },
    )
}

impl JobRegistry {
    async fn send_command(&self, command: impl Into<JobCommand>) {
        self.tx
            .send(command.into())
            .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.register_with_tree(pid, task_id, execution_key, script, mode, output_path, None)
            .await;
    }

    /// Registers a new running job whose process tree was started with
    /// [`Self::start_process_tree`]: the tree is part of the job from its
    /// first moment, so a kill never finds a job without it.
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn register_with_tree(
        &self,
        pid: u32,
        task_id: &str,
        execution_key: &str,
        script: &str,
        mode: TerminalMode,
        output_path: Option<PathBuf>,
        process_tree: Option<JobTree>,
    ) {
        self.send_command(StateCommand::Register {
            pid,
            task_id: task_id.to_string(),
            execution_key: execution_key.to_string(),
            script: script.to_string(),
            mode,
            output_path,
            process_tree,
        })
        .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(StateCommand::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(StateCommand::AttachKillSwitch { pid, kill_tx })
            .await;
    }

    /// Starts watching the process tree of a local job whose root shell is
    /// `pid`. Called right after the spawn and before [`Self::register`]:
    /// the tree follows the root from its first moments, while its children's
    /// lineage can still be read. The caller keeps `pid` unreaped until it
    /// calls [`JobTree::finish`].
    #[cfg_attr(target_os = "linux", allow(dead_code))]
    pub(crate) fn start_process_tree<E: executor_core::Executor>(
        &self,
        executor: &E,
        pid: u32,
        marker: &JobMarker,
    ) -> JobTree {
        JobTree::spawn(executor, self.scanner.clone(), pid, marker)
    }

    /// Appends stdout bytes for a running job.
    pub async fn append_stdout(&self, pid: u32, chunk: Vec<u8>) {
        self.send_command(StateCommand::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(StateCommand::AppendTerminalOutput {
            pid,
            stream: TerminalStream::Stderr,
            chunk,
        })
        .await;
    }

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

    /// Marks stderr stream closed.
    pub async fn close_stderr(&self, pid: u32) {
        self.send_command(StateCommand::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(JobRequest::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(JobRequest::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(JobRequest::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(JobRequest::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(JobRequest::ReadTerminalDelta {
            task_id: task_id.to_string(),
            cursor,
            max_bytes,
            tracked: true,
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Returns terminal output added since the provided cursor, without
    /// touching the unchanged-read tracker: the caller is the `monitor`
    /// pump, whose own cadence is not the model polling.
    ///
    /// # Errors
    /// Returns an error when the task id is unknown.
    pub async fn monitor_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(JobRequest::ReadTerminalDelta {
            task_id: task_id.to_string(),
            cursor,
            max_bytes,
            tracked: false,
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Whether every `reads` entry matches what the last read of that path
    /// returned — the fingerprint recorded by [`Self::record_file_reads`].
    /// `false` for an empty list or a path never recorded.
    pub async fn file_reads_unchanged(&self, reads: Vec<(PathBuf, FileFingerprint)>) -> bool {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobRequest::FileReadsUnchanged {
            reads,
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Records what a just-run script's file reads returned with; the next
    /// [`Self::file_reads_unchanged`] compares against these.
    pub async fn record_file_reads(&self, reads: Vec<(PathBuf, FileFingerprint)>) {
        self.send_command(StateCommand::RecordFileReads { reads })
            .await;
    }

    /// Marks a job as completed.
    pub async fn complete(&self, pid: u32, exit_code: i32, output_path: Option<PathBuf>) {
        self.send_command(StateCommand::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(StateCommand::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(JobRequest::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(JobRequest::Get {
            pid,
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Gets information about a specific job by its task ID.
    pub async fn get_by_task_id(&self, task_id: &str) -> Option<JobInfo> {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobRequest::GetByTaskId {
            task_id: task_id.to_string(),
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// Gets information about a job by its task ID once no kill of it is in
    /// flight. A job whose process has exited from a kill's signal still reads
    /// `Running` until the kill records its outcome; this waits for that
    /// outcome, so the status it returns is the job's real ending.
    pub async fn get_by_task_id_settled(&self, task_id: &str) -> Option<JobInfo> {
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobRequest::GetByTaskIdSettled {
            task_id: task_id.to_string(),
            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(JobRequest::BeginKill {
            pid,
            reply: reply_tx,
        })
        .await;
        let plan = Self::recv_reply(reply_rx).await;
        self.finish_kill(pid, plan).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(JobRequest::BeginKillByTaskId {
            task_id: task_id.to_string(),
            reply: reply_tx,
        })
        .await;
        match Self::recv_reply(reply_rx).await {
            Some((pid, plan)) => self.finish_kill(pid, plan).await,
            None => false,
        }
    }

    /// Kills every job that is still running in this registry.
    pub async fn kill_running(&self) -> usize {
        let jobs = self.list().await;
        futures::future::join_all(
            jobs.into_iter()
                .filter(|job| job.status == JobStatus::Running)
                .map(|job| self.kill(job.pid)),
        )
        .await
        .into_iter()
        .filter(|killed| *killed)
        .count()
    }

    /// 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(JobRequest::BeginKillByExecutionKey {
            execution_key: execution_key.to_string(),
            reply: reply_tx,
        })
        .await;
        let plans = Self::recv_reply(reply_rx).await;
        futures::future::join_all(
            plans
                .into_iter()
                .map(|(pid, plan)| self.finish_kill(pid, plan)),
        )
        .await
        .into_iter()
        .filter(|killed| *killed)
        .count()
    }

    /// Runs the kill a [`KillPlan`] describes and records its outcome.
    async fn finish_kill(&self, pid: u32, plan: KillPlan) -> bool {
        let killed = match plan {
            KillPlan::Done(killed) => return killed,
            KillPlan::Tree(tree) => match tree.kill().await {
                Ok(()) => true,
                #[cfg(unix)]
                Err(KillTreeError::Ended) => {
                    tracing::debug!(pid = %pid, "the job ended before the kill reached it");
                    false
                }
                Err(error) => {
                    tracing::warn!(pid = %pid, error = %error, "failed to kill job");
                    false
                }
            },
            KillPlan::Group(group) => match crate::process_tree::kill_process_tree(group).await {
                Ok(()) => true,
                Err(error) => {
                    tracing::warn!(pid = %pid, error = %error, "failed to kill job");
                    false
                }
            },
        };
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        self.send_command(JobRequest::EndKill {
            pid,
            killed,
            reply: reply_tx,
        })
        .await;
        Self::recv_reply(reply_rx).await
    }

    /// 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(JobRequest::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(JobRequest::HasRunning { reply: reply_tx })
            .await;
        Self::recv_reply(reply_rx).await
    }
}

/// Per-session read tracking behind the unchanged-read refusal: what each
/// task's last `terminal_read` returned with, and each file's fingerprint
/// from its last read.
#[derive(Default)]
struct ReadTracker {
    /// Task id → the `(cursor, total_bytes, status)` its last read returned.
    delta_reads: HashMap<String, (usize, usize, JobStatus)>,
    /// Path → the fingerprint its last script read carried.
    file_reads: HashMap<PathBuf, FileFingerprint>,
}

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();
        let mut reads = ReadTracker::default();

        while let Ok(command) = self.rx.recv().await {
            match command {
                JobCommand::State(command) => {
                    handle_state_command(&mut jobs, &mut reads, command).await;
                }
                JobCommand::Request(request) => {
                    handle_job_request(&mut jobs, &mut reads, request).await;
                }
            }
        }
    }
}

async fn handle_state_command(
    jobs: &mut HashMap<u32, JobState>,
    reads: &mut ReadTracker,
    command: StateCommand,
) {
    match command {
        StateCommand::Register {
            pid,
            task_id,
            execution_key,
            script,
            mode,
            output_path,
            process_tree,
        } => {
            register_job(jobs, pid, task_id, execution_key, script, mode, output_path);
            if let Some(job) = jobs.get_mut(&pid) {
                job.process_tree = process_tree;
            }
        }
        StateCommand::AttachTerminalInput { pid, input_tx } => {
            if let Some(job) = jobs.get_mut(&pid) {
                job.input_tx = Some(input_tx);
            }
        }
        StateCommand::AttachKillSwitch { pid, kill_tx } => {
            if let Some(job) = jobs.get_mut(&pid) {
                job.kill_switch = Some(kill_tx);
            }
        }
        StateCommand::AppendTerminalOutput { pid, stream, chunk } => {
            append_terminal_output(jobs, pid, stream, chunk).await;
        }
        StateCommand::CloseTerminalStream { pid, stream } => {
            close_terminal_stream(jobs, pid, stream);
        }
        StateCommand::Complete {
            pid,
            exit_code,
            output_path,
        } => complete_job(jobs, pid, exit_code, output_path).await,
        StateCommand::Fail {
            pid,
            error,
            output_path,
        } => fail_job(jobs, pid, error, output_path).await,
        StateCommand::RecordFileReads { reads: new_reads } => {
            reads.file_reads.extend(new_reads);
        }
    }
}

async fn handle_job_request(
    jobs: &mut HashMap<u32, JobState>,
    reads: &mut ReadTracker,
    request: JobRequest,
) {
    match request {
        JobRequest::List { reply } => {
            let items = jobs.values().map(|state| state.info.clone()).collect();
            let _ = reply.send(items).await;
        }
        JobRequest::Get { pid, reply } => {
            let item = jobs.get(&pid).map(|state| state.info.clone());
            let _ = reply.send(item).await;
        }
        JobRequest::GetByTaskId { task_id, reply } => {
            let item = find_pid_by_task_id(jobs, &task_id)
                .and_then(|pid| jobs.get(&pid))
                .map(|state| state.info.clone());
            let _ = reply.send(item).await;
        }
        JobRequest::GetByTaskIdSettled { task_id, reply } => {
            get_settled_by_task_id(jobs, &task_id, reply).await;
        }
        JobRequest::BeginKill { pid, reply } => {
            let plan = begin_kill(jobs, pid).await;
            let _ = reply.send(plan).await;
        }
        JobRequest::BeginKillByTaskId { task_id, reply } => {
            let plan = match find_pid_by_task_id(jobs, &task_id) {
                Some(pid) => Some((pid, begin_kill(jobs, pid).await)),
                None => None,
            };
            let _ = reply.send(plan).await;
        }
        JobRequest::BeginKillByExecutionKey {
            execution_key,
            reply,
        } => {
            let plans = begin_kill_by_execution_key(jobs, &execution_key).await;
            let _ = reply.send(plans).await;
        }
        JobRequest::EndKill { pid, killed, reply } => {
            let result = end_kill(jobs, pid, killed).await;
            release_settled_waiters(jobs, pid).await;
            let _ = reply.send(result).await;
        }
        JobRequest::InputTerminal {
            task_id,
            bytes,
            reply,
        } => {
            let result = input_terminal(jobs, &task_id, bytes).await;
            let _ = reply.send(result).await;
        }
        JobRequest::StartOutputRedirect {
            task_id,
            output_path,
            reply,
        } => {
            let result = redirect_task_output(jobs, &task_id, output_path).await;
            let _ = reply.send(result).await;
        }
        JobRequest::TerminalOutput { pid, reply } => {
            send_terminal_output(jobs, pid, reply).await;
        }
        JobRequest::ReadTerminalDelta {
            task_id,
            cursor,
            max_bytes,
            tracked,
            reply,
        } => {
            let result = read_terminal_delta(jobs, &task_id, cursor, max_bytes, !tracked)
                .and_then(|delta| tracked_delta(reads, &task_id, delta, tracked));
            let _ = reply.send(result).await;
        }
        JobRequest::FileReadsUnchanged {
            reads: paths,
            reply,
        } => {
            let unchanged = !paths.is_empty()
                && paths
                    .iter()
                    .all(|(path, stamp)| reads.file_reads.get(path) == Some(stamp));
            let _ = reply.send(unchanged).await;
        }
        JobRequest::TerminalStreamsClosed { pid, reply } => {
            let closed = jobs
                .get(&pid)
                .is_some_and(|job| job.stdout_closed && job.stderr_closed);
            let _ = reply.send(closed).await;
        }
        JobRequest::FormatRunning { reply } => {
            let _ = reply.send(format_running_jobs(jobs)).await;
        }
        JobRequest::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(),
            line_buffer: Vec::new(),
            stdout_partial: Vec::new(),
            stderr_partial: Vec::new(),
            stdout_buffer: Vec::new(),
            stderr_buffer: Vec::new(),
            stdout_closed: false,
            stderr_closed: false,
            input_tx: None,
            kill_switch: None,
            process_tree: None,
            kills_in_flight: 0,
            deferred_end: None,
            settled_waiters: Vec::new(),
            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"
            );
        }
        let (buffer, partial) = match stream {
            TerminalStream::Stdout => (&mut job.stdout_buffer, &mut job.stdout_partial),
            TerminalStream::Stderr => (&mut job.stderr_buffer, &mut job.stderr_partial),
        };
        buffer.extend_from_slice(&chunk);
        partial.extend_from_slice(&chunk);
        // Each stream completes its own lines; a line reaches the line
        // buffer whole, so one stream never interrupts the other's.
        if let Some(last_newline) = partial.iter().rposition(|byte| *byte == b'\n') {
            job.line_buffer.extend(partial.drain(..=last_newline));
        }
    }
}

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 job.kills_in_flight > 0 {
            job.deferred_end = Some(Ending::Complete {
                exit_code,
                output_path,
            });
            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;
        }
        if job.kills_in_flight > 0 {
            job.deferred_end = Some(Ending::Fail { error, output_path });
            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 begin_kill_by_execution_key(
    jobs: &mut HashMap<u32, JobState>,
    execution_key: &str,
) -> Vec<(u32, KillPlan)> {
    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 plans = Vec::with_capacity(pids.len());
    for pid in pids {
        plans.push((pid, begin_kill(jobs, pid).await));
    }
    plans
}

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
}

/// A read returning what the last read of this task returned is a poll:
/// nothing new arrived. Refuse it so the agent waits for the completion
/// event instead. Untracked reads — the `monitor` pump's own cadence —
/// neither refuse nor update the tracker.
fn tracked_delta(
    reads: &mut ReadTracker,
    task_id: &str,
    delta: TerminalDelta,
    tracked: bool,
) -> Result<TerminalDelta, String> {
    let returned = (delta.cursor, delta.total_bytes, delta.status.clone());
    if !tracked {
        return Ok(delta);
    }
    if reads.delta_reads.get(task_id) == Some(&returned) {
        Err(crate::poll_guard::unchanged_task_read(task_id))
    } else {
        reads.delta_reads.insert(task_id.to_string(), returned);
        Ok(delta)
    }
}

fn read_terminal_delta(
    jobs: &HashMap<u32, JobState>,
    task_id: &str,
    cursor: usize,
    max_bytes: usize,
    lines: bool,
) -> 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, lines),
            )
        },
    )
}

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
        }
    })
}

/// Starts killing a job: decides at once what needs no process signal, and
/// otherwise hands back what the caller must kill outside the registry.
async fn begin_kill(jobs: &mut HashMap<u32, JobState>, pid: u32) -> KillPlan {
    let Some(job) = jobs.get_mut(&pid) else {
        return KillPlan::Done(false);
    };
    if !matches!(job.info.status, JobStatus::Running) {
        tracing::warn!(pid = %pid, "cannot kill non-running job");
        return KillPlan::Done(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 KillPlan::Done(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 KillPlan::Done(true);
    }

    job.kills_in_flight += 1;
    job.process_tree
        .as_ref()
        .map_or(KillPlan::Group(pid), |tree| KillPlan::Tree(tree.clone()))
}

/// Records the outcome of a kill that ran outside the registry. A job whose
/// own flow ended it meanwhile takes that ending only when the kill failed.
async fn end_kill(jobs: &mut HashMap<u32, JobState>, pid: u32, killed: bool) -> bool {
    let Some(job) = jobs.get_mut(&pid) else {
        return false;
    };
    job.kills_in_flight = job.kills_in_flight.saturating_sub(1);
    if killed {
        job.deferred_end = None;
        if matches!(job.info.status, JobStatus::Running) {
            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;
    }
    // While another kill of the job still runs, `complete_job` and `fail_job`
    // defer the ending again.
    match job.deferred_end.take() {
        Some(Ending::Complete {
            exit_code,
            output_path,
        }) => complete_job(jobs, pid, exit_code, output_path).await,
        Some(Ending::Fail { error, output_path }) => {
            fail_job(jobs, pid, error, output_path).await;
        }
        None => {}
    }
    false
}

/// Answers a settled read at once, or parks it while a kill of the job runs.
async fn get_settled_by_task_id(
    jobs: &mut HashMap<u32, JobState>,
    task_id: &str,
    reply: Sender<Option<JobInfo>>,
) {
    match find_pid_by_task_id(jobs, task_id).and_then(|pid| jobs.get_mut(&pid)) {
        Some(job) if job.kills_in_flight > 0 => job.settled_waiters.push(reply),
        Some(job) => {
            let _ = reply.send(Some(job.info.clone())).await;
        }
        None => {
            let _ = reply.send(None).await;
        }
    }
}

/// Answers the callers parked on a job once its last kill in flight ended.
async fn release_settled_waiters(jobs: &mut HashMap<u32, JobState>, pid: u32) {
    let Some(job) = jobs.get_mut(&pid) else {
        return;
    };
    if job.kills_in_flight > 0 {
        return;
    }
    for waiter in std::mem::take(&mut job.settled_waiters) {
        let _ = waiter.send(Some(job.info.clone())).await;
    }
}

/// The bytes of a script a running-jobs line shows.
const SCRIPT_PREVIEW_BYTES: usize = 50;

/// The start of `script`, cut at a character boundary at or below
/// [`SCRIPT_PREVIEW_BYTES`] bytes.
fn script_preview(script: &str) -> String {
    if script.len() <= SCRIPT_PREVIEW_BYTES {
        return script.to_string();
    }
    let end = (0..=SCRIPT_PREVIEW_BYTES)
        .rev()
        .find(|index| script.is_char_boundary(*index))
        .unwrap_or(0);
    format!("{}...", &script[..end])
}

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 = script_preview(&job.info.script);

        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,
    lines: bool,
) -> Result<TerminalDelta, String> {
    let buffer = if lines {
        &job.line_buffer
    } else {
        &job.terminal_buffer
    };
    let total_bytes = 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: 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;

    fn spawn_registry() -> JobRegistry {
        let (registry, service) = job_registry_channel();
        TokioGlobal
            .spawn(async move { service.serve().await })
            .detach();
        registry
    }

    #[tokio::test]
    async fn unchanged_terminal_read_is_refused_then_succeeds_after_new_output() {
        let registry = spawn_registry();
        registry
            .register(7, "task-a", "exec-a", "run", TerminalMode::Sandboxed, None)
            .await;
        registry.append_stdout(7, b"one".to_vec()).await;

        let first = registry
            .terminal_read("task-a", 0, 1024)
            .await
            .expect("first read succeeds");
        let second = registry.terminal_read("task-a", first.cursor, 1024).await;
        assert!(
            second.is_err(),
            "an unchanged repeat read must be refused: {second:?}"
        );

        registry.append_stdout(7, b"two".to_vec()).await;
        let third = registry
            .terminal_read("task-a", first.cursor, 1024)
            .await
            .expect("read succeeds once output changed");
        assert_eq!(third.bytes, b"two");
    }

    #[tokio::test]
    async fn file_reads_track_unchanged_fingerprints() {
        let registry = spawn_registry();
        let dir = tempdir().expect("tempdir");
        let path = dir.path().join("log.txt");
        std::fs::write(&path, "v1").expect("write");
        let meta = std::fs::metadata(&path).expect("metadata");
        let reads = vec![(path.clone(), (meta.len(), meta.modified().ok()))];

        assert!(!registry.file_reads_unchanged(reads.clone()).await);
        registry.record_file_reads(reads.clone()).await;
        assert!(registry.file_reads_unchanged(reads).await);

        std::fs::write(&path, "v1-longer").expect("rewrite");
        let meta = std::fs::metadata(&path).expect("metadata");
        let changed = vec![(path, (meta.len(), meta.modified().ok()))];
        assert!(!registry.file_reads_unchanged(changed).await);
    }

    #[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);
    }

    /// The rotation case: tail writes `tail: ` on stderr, the new file's line
    /// arrives on stdout, then the rest of the notice on stderr. The monitor
    /// reads whole lines, while the merged terminal buffer stays in arrival
    /// order.
    #[tokio::test]
    async fn monitor_reads_whole_lines_when_partial_writes_interleave() {
        let (registry, service) = job_registry_channel();
        TokioGlobal
            .spawn(async move { service.serve().await })
            .detach();
        registry
            .register(
                203,
                "task-lines",
                "exec-lines",
                "tail -F f",
                TerminalMode::Sandboxed,
                None,
            )
            .await;
        registry.append_stderr(203, b"tail: ".to_vec()).await;
        registry.append_stdout(203, b"rotated\n".to_vec()).await;
        registry
            .append_stderr(203, b"'f' has been replaced\n".to_vec())
            .await;
        registry.append_stdout(203, b"unfinished".to_vec()).await;

        let lines = registry
            .monitor_read("task-lines", 0, usize::MAX)
            .await
            .unwrap();
        assert_eq!(
            String::from_utf8_lossy(&lines.bytes),
            "rotated\ntail: 'f' has been replaced\n"
        );
        let merged = registry
            .terminal_read("task-lines", 0, usize::MAX)
            .await
            .unwrap();
        assert_eq!(
            String::from_utf8_lossy(&merged.bytes),
            "tail: rotated\n'f' has been replaced\nunfinished"
        );
    }

    #[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));
    }

    /// A script longer than the preview, with a multibyte character across
    /// the cut, is listed instead of panicking inside the registry.
    #[tokio::test]
    async fn test_format_running_jobs_cuts_a_multibyte_script_at_a_boundary() {
        let (registry, service) = job_registry_channel();
        TokioGlobal
            .spawn(async move { service.serve().await })
            .detach();

        // Three bytes per character: byte 50 lies inside the 17th.
        let script = "æ—¥".repeat(30);
        assert!(!script.is_char_boundary(SCRIPT_PREVIEW_BYTES));
        registry
            .register(
                1,
                "task-cjk",
                "exec-cjk",
                &script,
                TerminalMode::Sandboxed,
                None,
            )
            .await;

        let running = registry.format_running_jobs().await;
        assert!(
            running.contains(&format!("`{}...`", "æ—¥".repeat(16))),
            "{running}"
        );
        assert_eq!(script_preview("short"), "short");
        assert_eq!(script_preview(&"x".repeat(50)), "x".repeat(50));
        assert_eq!(
            script_preview(&"x".repeat(51)),
            format!("{}...", "x".repeat(50))
        );
    }

    fn running_job(pid: u32) -> HashMap<u32, JobState> {
        let mut jobs = HashMap::new();
        register_job(
            &mut jobs,
            pid,
            "task".to_string(),
            "exec".to_string(),
            "true".to_string(),
            TerminalMode::Sandboxed,
            None,
        );
        jobs
    }

    /// Two kills of one job overlap: the first to end must not release an
    /// ending the job's own flow reported while the second still runs.
    #[tokio::test]
    async fn overlapping_kills_hold_the_deferred_ending_until_the_last_ends() {
        let mut jobs = running_job(7);
        assert!(matches!(begin_kill(&mut jobs, 7).await, KillPlan::Group(7)));
        assert!(matches!(begin_kill(&mut jobs, 7).await, KillPlan::Group(7)));
        complete_job(&mut jobs, 7, 0, None).await;
        assert_eq!(jobs[&7].info.status, JobStatus::Running, "the ending waits");

        assert!(!end_kill(&mut jobs, 7, false).await);
        assert_eq!(
            jobs[&7].info.status,
            JobStatus::Running,
            "the other kill still runs"
        );
        assert!(!end_kill(&mut jobs, 7, false).await);
        assert_eq!(
            jobs[&7].info.status,
            JobStatus::Completed { exit_code: 0 },
            "the last kill to fail releases the ending"
        );
    }

    /// A kill that succeeds wins over an ending reported while it ran.
    #[tokio::test]
    async fn a_successful_kill_wins_over_a_deferred_ending() {
        let mut jobs = running_job(8);
        assert!(matches!(begin_kill(&mut jobs, 8).await, KillPlan::Group(8)));
        complete_job(&mut jobs, 8, 0, None).await;
        assert!(end_kill(&mut jobs, 8, true).await);
        assert_eq!(jobs[&8].info.status, JobStatus::Killed);
    }

    /// A job whose process exited from a kill's signal reads as running until
    /// the kill records its outcome; the settled read waits for it.
    #[tokio::test]
    async fn the_settled_read_waits_for_a_kill_in_flight() {
        let (registry, service) = job_registry_channel();
        TokioGlobal
            .spawn(async move { service.serve().await })
            .detach();
        registry
            .register(
                557,
                "task-settled",
                "exec-settled",
                "sleep 10",
                TerminalMode::Sandboxed,
                None,
            )
            .await;
        let (reply_tx, reply_rx) = async_channel::bounded(1);
        registry
            .send_command(JobRequest::BeginKill {
                pid: 557,
                reply: reply_tx,
            })
            .await;
        let plan = JobRegistry::recv_reply(reply_rx).await;
        assert!(matches!(plan, KillPlan::Group(557)));
        // The killed process exits and its flow reports completion while the
        // kill has not returned.
        registry.complete(557, 137, None).await;
        let running = registry.get_by_task_id("task-settled").await;
        assert!(matches!(
            running.expect("job should exist").status,
            JobStatus::Running
        ));

        let waiting = {
            let registry = registry.clone();
            tokio::spawn(async move { registry.get_by_task_id_settled("task-settled").await })
        };
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        assert!(!waiting.is_finished(), "the kill is still in flight");

        let (reply_tx, reply_rx) = async_channel::bounded(1);
        registry
            .send_command(JobRequest::EndKill {
                pid: 557,
                killed: true,
                reply: reply_tx,
            })
            .await;
        assert!(JobRegistry::recv_reply(reply_rx).await);
        let job = waiting.await.unwrap().expect("job should exist");
        assert!(matches!(job.status, JobStatus::Killed));
    }
}