devsandbox 0.9.0

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
//! Verbs as requests (docs/reference/api.md, *Verbs*;
//! docs/architecture/daemon/verbs.md): `run`, `rebuild`, `start`, `stop` and
//! `rm` as API methods, and `services.rebuild` and `gc` (no instance verbs:
//! `service rebuild <name>`, `gc [--force]`). The daemon runs each as a `devsandbox --in-process -C
//! <root> <verb> …` subprocess built from the request's typed params
//! ([`argv`]), so a verb that panics or hangs takes down one request, not the
//! daemon, and a handoff doesn't wait for a build
//! (docs/architecture/daemon/verbs.md, *Why a subprocess*).
//!
//! The subprocess gets the request's env and nothing of the daemon's
//! (`${localEnv:…}`, `SSH_AUTH_SOCK`, `GIT_*` must be the caller's), its own
//! process group (a cancel reaches docker and git under it), null stdin (no
//! prompt can block) and `GIT_TERMINAL_PROMPT=0`. Its stdout and stderr go
//! to spool files, `<data-dir>/devsandbox/logs/verbs/<pid>.out|.err`, not
//! pipes: a daemon exiting mid-verb (handoff, crash) would EPIPE a pipe, and
//! `stop`/`rm` have no build-log tee to fall back on. The files are removed
//! once the exit is reported; a successor finds live verbs by them and holds
//! itself open until they exit ([`InFlight::adopt`]).
//!
//! One loop on the connection's thread per request ([`serve`]): copy new
//! spool bytes into `output` notifications, re-read `state.toml` for
//! `progress`, reap the child, and watch the socket ([`Peer`]): a hang-up
//! SIGINTs the group (the verb rolls back), unless the request is `detach`
//! or the daemon is draining, whose read-side shutdown looks the same and
//! must not cancel anything.
//! Socket-free, so the loop is tested with a fake [`Peer`] and `sh` scripts.

use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsString;
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use anyhow::Context;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use super::api::{self, ApiError};
use crate::state::{PhaseView, Progress, State};

/// How long one turn of the loop waits on the socket: the output latency.
const TICK: Duration = Duration::from_millis(50);
/// How often `state.toml` is re-read for `progress`.
const STATE_POLL: Duration = Duration::from_millis(250);
/// Most bytes one `output` notification carries (escaped, well under
/// `proto::MAX_LINE`).
const CHUNK: usize = 64 * 1024;
/// How much of stderr is kept for a `failed` message.
const ERR_TAIL: usize = 16 * 1024;

pub fn is_verb(method: &str) -> bool {
    matches!(method, "run" | "rebuild" | "start" | "stop" | "rm" | "services.rebuild" | "gc")
}

// ---- params ---------------------------------------------------------------

pub use crate::build_log::TtySize;

/// `run` params. `env` is required on every verb: never the daemon's own.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RunParams {
    pub root: PathBuf,
    pub env: BTreeMap<String, String>,
    pub sandbox: String,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub branch: Option<String>,
    #[serde(default)]
    pub base: Option<String>,
    #[serde(default)]
    pub json: bool,
    /// Probe the runtime's identity mode afresh (`--reprobe`).
    #[serde(default)]
    pub reprobe: bool,
    #[serde(default)]
    pub detach: bool,
    /// Run its commands on a pty of this size (the build log's tee, as
    /// [`crate::build_log::TTY_ENV`]): coloured output and docker build's
    /// TTY progress, as on the caller's terminal. Absent: pipes.
    #[serde(default)]
    pub tty: Option<TtySize>,
    /// Ask the fleet's hub where to run it (`run --place`;
    /// docs/architecture/daemon/fleet.md, *Placement*). Absent, it runs on
    /// this host: a typed run is never placed. Only the daemon reads it:
    /// the subprocess runs here either way.
    #[serde(default)]
    pub place: bool,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RebuildParams {
    pub root: PathBuf,
    pub env: BTreeMap<String, String>,
    #[serde(default)]
    pub instance: Option<String>,
    #[serde(default)]
    pub all: bool,
    #[serde(default)]
    pub force: bool,
    /// As [`RunParams::reprobe`].
    #[serde(default)]
    pub reprobe: bool,
    #[serde(default)]
    pub detach: bool,
    /// As [`RunParams::tty`].
    #[serde(default)]
    pub tty: Option<TtySize>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StartParams {
    pub root: PathBuf,
    pub env: BTreeMap<String, String>,
    #[serde(default)]
    pub instance: Option<String>,
    #[serde(default)]
    pub all: bool,
    #[serde(default)]
    pub detach: bool,
    /// As [`RunParams::tty`].
    #[serde(default)]
    pub tty: Option<TtySize>,
}

/// `stop` params. `detach`, as on `rm` and `services.rebuild` (held verbs),
/// only means "not cancelled when the client leaves": the answer still comes
/// at the exit, and a hang-up before it leaves the verb running. The
/// dashboard always sends it (a quit mustn't interrupt its `stop`); the CLI
/// never does (Ctrl-C = hang-up = cancel).
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StopParams {
    pub root: PathBuf,
    pub env: BTreeMap<String, String>,
    #[serde(default)]
    pub instance: Option<String>,
    #[serde(default)]
    pub all: bool,
    #[serde(default)]
    pub detach: bool,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RmParams {
    pub root: PathBuf,
    pub env: BTreeMap<String, String>,
    pub instance: String,
    /// `true` deletes the branch, `false` keeps it, absent takes the
    /// non-TTY default (merged or gone branches deleted, local work kept).
    #[serde(default)]
    pub delete_branch: Option<bool>,
    #[serde(default)]
    pub force: bool,
    /// Answer `confirm` (the branch question) instead of deciding off a TTY,
    /// having removed nothing: the client asks and resends with
    /// `deleteBranch`.
    #[serde(default)]
    pub ask: bool,
    /// Not cancelled by a hang-up; still answered at the exit (see
    /// [`StopParams`]).
    #[serde(default)]
    pub detach: bool,
}

/// `services.rebuild` params: a service of the config root, by name.
/// `detach` never answers early (no instance would show it running on): it
/// only keeps a hang-up from cancelling it (see [`StopParams`]).
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ServicesRebuildParams {
    pub root: PathBuf,
    pub env: BTreeMap<String, String>,
    pub name: String,
    #[serde(default)]
    pub detach: bool,
}

/// `gc` params: the config root whose unused services and networks go
/// (`commands::services::gc`; its agent-link sweep is host-wide). Without
/// `force` the orphaned shell-history files are kept: their confirm prompt
/// has no TTY in the subprocess, so it answers no. `detach` as on
/// [`ServicesRebuildParams`].
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GcParams {
    pub root: PathBuf,
    pub env: BTreeMap<String, String>,
    #[serde(default)]
    pub force: bool,
    #[serde(default)]
    pub detach: bool,
}

/// What a verb acts on: an instance as the CLI's `<name>` takes it, or `--all`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target {
    One(String),
    All,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verb {
    Run { sandbox: String, name: Option<String>, branch: Option<String>, base: Option<String>, json: bool, reprobe: bool },
    Rebuild { target: Target, force: bool, reprobe: bool },
    Start { target: Target },
    Stop { target: Target },
    Rm { instance: String, delete_branch: Option<bool>, force: bool, ask: bool },
    /// A service, not an instance: answers `instance: null`.
    ServicesRebuild { name: String },
    /// Host maintenance of the root, no instance: answers `instance: null`.
    Gc { force: bool },
}

impl Verb {
    /// The CLI's words for it: the subprocess's subcommand (split on the
    /// space) and what log lines and `failed` messages call it.
    pub fn name(&self) -> &'static str {
        match self {
            Verb::Run { .. } => "run",
            Verb::Rebuild { .. } => "rebuild",
            Verb::Start { .. } => "start",
            Verb::Stop { .. } => "stop",
            Verb::Rm { .. } => "rm",
            Verb::ServicesRebuild { .. } => "service rebuild",
            Verb::Gc { .. } => "gc",
        }
    }

    fn target(&self) -> Option<&Target> {
        match self {
            Verb::Rebuild { target, .. } | Verb::Start { target } | Verb::Stop { target } => Some(target),
            Verb::Run { .. } | Verb::Rm { .. } | Verb::ServicesRebuild { .. } | Verb::Gc { .. } => None,
        }
    }

    /// The instance name the request gave, if it names one.
    fn named(&self) -> Option<&str> {
        match self {
            Verb::Rm { instance, .. } => Some(instance),
            _ => match self.target() {
                Some(Target::One(name)) => Some(name),
                _ => None,
            },
        }
    }
}

/// A checked verb request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerbRequest {
    /// Absolute config root (`-C`).
    pub root: PathBuf,
    /// The subprocess's whole env.
    pub env: BTreeMap<String, String>,
    pub verb: Verb,
    pub detach: bool,
    /// The pty size its build log tees through (`run`/`rebuild`/`start`).
    pub tty: Option<TtySize>,
}

/// Params of verb `method` into a [`VerbRequest`]: `invalid` for bad params
/// (a relative `root`, a missing `env`, `instance` and `all` both or
/// neither, a `tty` side 0 or over [`TtySize::MAX`]), `not-found` for a
/// `root` that isn't a directory.
pub fn parse(method: &str, params: Value) -> Result<VerbRequest, ApiError> {
    let (root, env, verb, detach, tty) = match method {
        "run" => {
            let p: RunParams = api::parse(params)?;
            let verb =
                Verb::Run { sandbox: p.sandbox, name: p.name, branch: p.branch, base: p.base, json: p.json, reprobe: p.reprobe };
            (p.root, p.env, verb, p.detach, p.tty)
        }
        "rebuild" => {
            let p: RebuildParams = api::parse(params)?;
            let verb = Verb::Rebuild { target: target(p.instance, p.all)?, force: p.force, reprobe: p.reprobe };
            (p.root, p.env, verb, p.detach, p.tty)
        }
        "start" => {
            let p: StartParams = api::parse(params)?;
            (p.root, p.env, Verb::Start { target: target(p.instance, p.all)? }, p.detach, p.tty)
        }
        "stop" => {
            let p: StopParams = api::parse(params)?;
            (p.root, p.env, Verb::Stop { target: target(p.instance, p.all)? }, p.detach, None)
        }
        "rm" => {
            let p: RmParams = api::parse(params)?;
            let verb = Verb::Rm { instance: p.instance, delete_branch: p.delete_branch, force: p.force, ask: p.ask };
            (p.root, p.env, verb, p.detach, None)
        }
        "services.rebuild" => {
            let p: ServicesRebuildParams = api::parse(params)?;
            (p.root, p.env, Verb::ServicesRebuild { name: p.name }, p.detach, None)
        }
        "gc" => {
            let p: GcParams = api::parse(params)?;
            (p.root, p.env, Verb::Gc { force: p.force }, p.detach, None)
        }
        other => return Err(ApiError::unknown_method(other)),
    };
    if let Some(size) = tty
        && !size.valid()
    {
        return Err(ApiError::invalid(format!("`tty` sides must be 1 to {}, got {size}", TtySize::MAX)));
    }
    if !root.is_absolute() {
        return Err(ApiError::invalid(format!("`root` must be absolute, got `{}`", root.display())));
    }
    if !root.is_dir() {
        return Err(ApiError::not_found(format!("no directory {}", root.display())));
    }
    for (key, value) in &env {
        if key.is_empty() || key.contains(['=', '\0']) || value.contains('\0') {
            return Err(ApiError::invalid(format!("bad `env` entry `{key}`")));
        }
    }
    Ok(VerbRequest { root, env, verb, detach, tty })
}

fn target(instance: Option<String>, all: bool) -> Result<Target, ApiError> {
    match (instance, all) {
        (Some(name), false) => Ok(Target::One(name)),
        (None, true) => Ok(Target::All),
        (Some(_), true) => Err(ApiError::invalid("give `instance` or `all: true`, not both")),
        (None, false) => Err(ApiError::invalid("missing `instance` (or `all: true`)")),
    }
}

/// The subprocess's arguments: `--in-process -C <root> <verb> --flag=value …
/// -- <target>`. `--flag=value` and `--` keep a value starting with `-` a
/// value; the target always goes in, so no pick prompt can come up.
pub fn argv(req: &VerbRequest) -> Vec<String> {
    let mut args = vec!["--in-process".to_string(), "-C".into(), req.root.to_string_lossy().into_owned()];
    args.extend(req.verb.name().split(' ').map(String::from));
    let flag = |args: &mut Vec<String>, name: &str, value: &Option<String>| {
        if let Some(value) = value {
            args.push(format!("--{name}={value}"));
        }
    };
    let target = match &req.verb {
        Verb::Run { sandbox, name, branch, base, json, reprobe } => {
            flag(&mut args, "name", name);
            flag(&mut args, "branch", branch);
            flag(&mut args, "base", base);
            if *json {
                args.push("--json".into());
            }
            if *reprobe {
                args.push("--reprobe".into());
            }
            Some(sandbox)
        }
        Verb::Rebuild { target, force, reprobe } => {
            if *force {
                args.push("--force".into());
            }
            if *reprobe {
                args.push("--reprobe".into());
            }
            one_or_all(&mut args, target)
        }
        Verb::Start { target } | Verb::Stop { target } => one_or_all(&mut args, target),
        Verb::Rm { instance, delete_branch, force, ask } => {
            match delete_branch {
                Some(true) => args.push("--delete-branch".into()),
                Some(false) => args.push("--keep-branch".into()),
                None => {}
            }
            if *force {
                args.push("--force".into());
            }
            if *ask {
                args.push("--fail-on-ask".into());
            }
            Some(instance)
        }
        Verb::ServicesRebuild { name } => Some(name),
        Verb::Gc { force } => {
            if *force {
                args.push("--force".into());
            }
            None
        }
    };
    if let Some(target) = target {
        args.push("--".into());
        args.push(target.clone());
    }
    args
}

fn one_or_all<'a>(args: &mut Vec<String>, target: &'a Target) -> Option<&'a String> {
    match target {
        Target::One(name) => Some(name),
        Target::All => {
            args.push("--all".into());
            None
        }
    }
}

/// When a `detach` request is answered (docs/reference/api.md, *Verbs*).
/// Held verbs (`stop`, `rm`, `services.rebuild`, `gc`) answer at the exit, detached
/// or not: for them `detach` only means a hang-up leaves them running.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DetachAt {
    /// Not detached: at the exit.
    Never,
    /// Right after the spawn: nothing records the child's pid on one
    /// instance (`start`, `--all`).
    Spawn,
    /// Once an instance's `progress.pid` is the child's (`run`, `rebuild`).
    Registered,
}

fn detach_at(req: &VerbRequest) -> DetachAt {
    if !req.detach {
        return DetachAt::Never;
    }
    match &req.verb {
        Verb::Run { .. } | Verb::Rebuild { target: Target::One(_), .. } => DetachAt::Registered,
        Verb::Rebuild { .. } | Verb::Start { .. } => DetachAt::Spawn,
        Verb::Stop { .. } | Verb::Rm { .. } | Verb::ServicesRebuild { .. } | Verb::Gc { .. } => DetachAt::Never,
    }
}

// ---- wire values ----------------------------------------------------------

pub(crate) fn output_params(request: Option<u64>, stream: &str, data: &str) -> Value {
    json!({ "request": request, "stream": stream, "data": data })
}

fn progress_params(request: Option<u64>, instance: &str, phase: &str) -> Value {
    json!({ "request": request, "instance": instance, "phase": phase })
}

fn done_result(instance: Option<&str>) -> Value {
    json!({ "instance": instance, "exit": 0 })
}

fn detached_result(instance: Option<&str>, record: Option<Value>) -> Value {
    let mut v = json!({ "instance": instance, "detached": true });
    if let Some(record) = record {
        v["record"] = record;
    }
    v
}

fn failed_data(exit: i32, instance: Option<&str>) -> Value {
    json!({ "exit": exit, "instance": instance })
}

// ---- execution ------------------------------------------------------------

/// How the daemon runs verbs. Injectable so tests run `sh -c` scripts
/// against scratch files instead of devsandbox against the user's state.
#[derive(Debug, Clone)]
pub struct Runner {
    /// The program and its leading args ([`argv`] follows). Empty in
    /// production: the devsandbox binary, re-resolved per spawn
    /// ([`crate::exe::devsandbox`]) so verbs run the upgraded binary.
    pub program: Vec<OsString>,
    /// The spool dir: `<data-dir>/devsandbox/logs/verbs`.
    pub spool: PathBuf,
    /// The `state.toml` `progress` is read from.
    pub state: PathBuf,
}

impl Runner {
    pub fn new() -> anyhow::Result<Self> {
        let state = State::path()?;
        let spool = state.parent().context("no data dir")?.join("logs").join("verbs");
        Ok(Self { program: Vec::new(), spool, state })
    }
}

/// The verbs in flight: the `verbs` holder count. Our own subprocesses not
/// reaped yet, by pid, detached ones included; and the *adopted* ones, verbs
/// a previous daemon left running at its exit (handoff, idle, crash), found
/// by their spool files at start ([`InFlight::adopt`]). Those aren't our
/// children: they're polled with `pid_alive`, never waited on.
#[derive(Debug, Default)]
pub struct InFlight {
    own: Mutex<BTreeMap<u32, &'static str>>,
    adopted: Mutex<BTreeSet<u32>>,
}

impl InFlight {
    pub fn len(&self) -> usize {
        self.own.lock().unwrap_or_else(|e| e.into_inner()).len()
            + self.adopted.lock().unwrap_or_else(|e| e.into_inner()).len()
    }

    fn insert(&self, pid: u32, verb: &'static str) {
        self.own.lock().unwrap_or_else(|e| e.into_inner()).insert(pid, verb);
    }

    fn remove(&self, pid: u32) {
        self.own.lock().unwrap_or_else(|e| e.into_inner()).remove(&pid);
    }

    /// The start sweep of `spool`: a live verb's files make it adopted (it
    /// holds the daemon until it exits), a dead one's are removed, and so
    /// are temp files whose daemon is gone (it died between create and
    /// rename). Only for a daemon holding the start lock: no predecessor is
    /// still draining, so every file is a leftover or a live orphan.
    pub fn adopt(&self, spool: &Path, log: fn(&str)) {
        let adopted = sweep(spool, &crate::state::pid_alive, log);
        for pid in &adopted {
            log(&format!("adopted verb (pid {pid}): left running by a previous daemon"));
        }
        self.adopted.lock().unwrap_or_else(|e| e.into_inner()).extend(adopted);
    }

    /// Drop the adopted verbs that have exited and remove their spool files.
    /// Cheap (a `kill(0)` each), so the accept loop calls it every tick.
    pub fn check_adopted(&self, spool: &Path, log: fn(&str)) {
        let mut adopted = self.adopted.lock().unwrap_or_else(|e| e.into_inner());
        adopted.retain(|&pid| {
            if crate::state::pid_alive(pid) {
                return true;
            }
            remove_spool(spool, pid);
            log(&format!("adopted verb (pid {pid}) exited"));
            false
        });
    }
}

/// A file in the spool dir, by its name (the rest isn't ours to touch).
#[derive(Debug, PartialEq, Eq)]
enum SpoolName {
    /// `<pid>.out|.err`: a verb's.
    Verb(u32),
    /// `.<daemon-pid>-<seq>.out.tmp|.err.tmp`: before the rename.
    Temp(u32),
}

fn spool_name(name: &str) -> Option<SpoolName> {
    fn pid(s: &str) -> Option<u32> {
        (!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.parse().ok()).flatten()
    }
    if let Some(temp) = name.strip_prefix('.').and_then(|n| n.strip_suffix(".tmp")) {
        let stem = temp.strip_suffix(".out").or_else(|| temp.strip_suffix(".err"))?;
        let (daemon, seq) = stem.split_once('-')?;
        pid(seq)?;
        return pid(daemon).map(SpoolName::Temp);
    }
    let stem = name.strip_suffix(".out").or_else(|| name.strip_suffix(".err"))?;
    pid(stem).map(SpoolName::Verb)
}

/// Remove the dead verbs' and dead daemons' files in `spool`; the live
/// verbs' pids. A missing dir has nothing in it.
fn sweep(spool: &Path, alive: &dyn Fn(u32) -> bool, log: fn(&str)) -> BTreeSet<u32> {
    let mut live = BTreeSet::new();
    let Ok(entries) = std::fs::read_dir(spool) else { return live };
    let mut dead = BTreeSet::new();
    for entry in entries.flatten() {
        let name = entry.file_name();
        let Some(kind) = name.to_str().and_then(spool_name) else { continue };
        match kind {
            SpoolName::Verb(pid) if alive(pid) => {
                live.insert(pid);
            }
            SpoolName::Verb(pid) => {
                dead.insert(pid);
            }
            SpoolName::Temp(daemon) if alive(daemon) => {}
            SpoolName::Temp(_) => {
                let _ = std::fs::remove_file(entry.path());
            }
        }
    }
    for pid in dead {
        remove_spool(spool, pid);
        log(&format!("removed the spool files of a finished verb (pid {pid})"));
    }
    live
}

fn remove_spool(spool: &Path, pid: u32) {
    let _ = std::fs::remove_file(spool.join(format!("{pid}.out")));
    let _ = std::fs::remove_file(spool.join(format!("{pid}.err")));
}

/// The requesting connection, as the loop sees it.
pub trait Peer {
    /// Write one notification, whole. An error means the client is gone.
    fn notify(&self, method: &str, params: Value) -> io::Result<()>;
    /// Wait up to `tick` for the client to hang up; `true` once it has.
    /// Pending data (a pipelined request) is not a hang-up.
    fn hung_up(&self, tick: Duration) -> bool;
    /// The daemon is draining: its read-side shutdown is what looked like a
    /// hang-up.
    fn draining(&self) -> bool;
}

/// A verb's answer, or `Gone`: the client hung up (or the daemon is
/// draining), so nothing is sent and the connection closes.
#[derive(Debug)]
pub enum Outcome {
    Answer(Result<Value, Failure>),
    Gone,
}

/// An error response, with `data` for `failed`.
#[derive(Debug)]
pub struct Failure {
    pub code: &'static str,
    pub message: String,
    pub data: Option<Value>,
}

impl From<ApiError> for Failure {
    fn from(e: ApiError) -> Self {
        Failure { code: e.code, message: e.message, data: None }
    }
}

/// Run `req` to its answer, streaming to `peer` (`request` is the id the
/// notifications carry). `who` names the connection in `log` lines.
pub fn serve(
    req: &VerbRequest,
    request: Option<u64>,
    runner: &Runner,
    table: &Arc<InFlight>,
    peer: &dyn Peer,
    who: &str,
    log: fn(&str),
) -> Outcome {
    let verb = req.verb.name();
    let before = State::load_at(&runner.state).unwrap_or_default();
    // What the answer names when no instance records the child's pid (a
    // no-op rebuild, `start`, `stop`, `rm`): the request's name, resolved
    // as the verb will (it gets the same name and never prompts).
    let resolved =
        req.verb.named().and_then(|name| crate::commands::resolve_instance_noninteractive(&before, name).ok());
    let mut running = match Running::spawn(runner, req) {
        Ok(running) => running,
        Err(e) => return Outcome::Answer(Err(ApiError::internal(e).into())),
    };
    let pid = running.pid;
    table.insert(pid, verb);
    log(&format!("{who}: {verb} started (pid {pid})"));
    let label = format!("{who}: {verb} (pid {pid})");
    let all = req.verb.target() == Some(&Target::All);
    let detach = detach_at(req);
    if detach == DetachAt::Spawn {
        let instance = if all { None } else { resolved.as_deref() };
        running.reap_later(Arc::clone(table), label, log);
        return Outcome::Answer(Ok(detached_result(instance, None)));
    }

    let mut tracker = Tracker::new(pid, before.instances.keys().cloned().collect());
    let mut next_poll = Instant::now();
    let status = loop {
        if let Err(e) = running.pump(request, peer) {
            return running.gone(peer, Left::after_write(&e, req.detach), Arc::clone(table), label, log);
        }
        match running.child.try_wait() {
            Ok(Some(status)) => break Ok(status),
            Ok(None) => {}
            Err(e) => break Err(e),
        }
        if Instant::now() >= next_poll {
            next_poll = Instant::now() + STATE_POLL;
            if let Ok(state) = State::load_at(&runner.state) {
                for (instance, phase) in tracker.observe(&state, Progress::current_view) {
                    if let Err(e) = peer.notify("progress", progress_params(request, &instance, &phase)) {
                        return running.gone(peer, Left::after_write(&e, req.detach), Arc::clone(table), label, log);
                    }
                }
                if let (DetachAt::Registered, Some(key)) = (detach, tracker.instance.clone()) {
                    let record = match &req.verb {
                        Verb::Run { json: true, .. } => state.instances.get(&key).and_then(|info| {
                            serde_json::to_value(crate::commands::run::RunRecord::new(&key, info)).ok()
                        }),
                        _ => None,
                    };
                    running.reap_later(Arc::clone(table), label, log);
                    return Outcome::Answer(Ok(detached_result(Some(&key), record)));
                }
            }
        }
        if peer.hung_up(TICK) {
            let left = if req.detach { Left::Detached } else { Left::HungUp };
            return running.gone(peer, left, Arc::clone(table), label, log);
        }
    };

    // Output before the answer: the files are complete now.
    let _ = running.pump(request, peer);
    let _ = running.flush(request, peer);
    let mut added = None;
    if let Ok(state) = State::load_at(&runner.state) {
        for (instance, phase) in tracker.observe(&state, Progress::current_view) {
            let _ = peer.notify("progress", progress_params(request, &instance, &phase));
        }
        added = matches!(req.verb, Verb::Run { .. }).then(|| tracker.added(&state)).flatten();
    }
    let stderr = String::from_utf8_lossy(&running.err.tail).into_owned();
    running.finish(table);
    let status = match status {
        Ok(status) => status,
        Err(e) => return Outcome::Answer(Err(ApiError::internal(anyhow::Error::new(e).context("cannot wait")).into())),
    };
    let exit = exit_code(status);
    log(&format!("{label} exited {exit}"));
    let instance = if all { None } else { tracker.instance.or(added).or(resolved) };
    if exit == 0 {
        return Outcome::Answer(Ok(done_result(instance.as_deref())));
    }
    let message = error_message(&stderr);
    if matches!(req.verb, Verb::Rm { ask: true, .. }) && exit == crate::commands::rm::NEEDS_ANSWER_EXIT {
        if let Some(question) = message {
            return Outcome::Answer(Err(Failure { code: "confirm", message: question, data: None }));
        }
    }
    Outcome::Answer(Err(Failure {
        code: "failed",
        message: message.unwrap_or_else(|| format!("`devsandbox {verb}` exited with {exit}")),
        data: Some(failed_data(exit, instance.as_deref())),
    }))
}

/// A spawned verb: the child and its two spool files.
struct Running {
    child: Child,
    pid: u32,
    out: Spool,
    err: Spool,
}

/// One spool file and the read side the loop tails.
struct Spool {
    path: PathBuf,
    file: File,
    /// The start of a UTF-8 sequence cut by the last read, sent with the next.
    held: Vec<u8>,
    /// The last [`ERR_TAIL`] bytes, kept for stderr only.
    tail: Vec<u8>,
    keep_tail: bool,
}

impl Running {
    fn spawn(runner: &Runner, req: &VerbRequest) -> anyhow::Result<Running> {
        static SEQ: AtomicU64 = AtomicU64::new(0);
        // Before the spool files, so a failure leaves none behind.
        let (program, lead) = match runner.program.split_first() {
            Some((program, lead)) => (program.clone(), lead),
            None => {
                let exe = crate::exe::devsandbox().context("cannot locate the devsandbox binary")?;
                (exe.into_os_string(), &[][..])
            }
        };
        std::fs::create_dir_all(&runner.spool).with_context(|| format!("cannot create {}", runner.spool.display()))?;
        // Temp names until the pid is known; the daemon's pid keeps two
        // daemons' (a draining one and its successor) apart.
        let stem = format!(".{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed));
        let (out_w, out) = Spool::create(&runner.spool.join(format!("{stem}.out.tmp")), false)?;
        let (err_w, err) = match Spool::create(&runner.spool.join(format!("{stem}.err.tmp")), true) {
            Ok(created) => created,
            Err(e) => {
                let _ = std::fs::remove_file(&out.path);
                return Err(e);
            }
        };
        let mut cmd = Command::new(&program);
        cmd.args(lead)
            .args(argv(req))
            .stdin(Stdio::null())
            .stdout(out_w)
            .stderr(err_w)
            .env_clear()
            .envs(&req.env)
            .env("GIT_TERMINAL_PROMPT", "0");
        // The request's size, never one the caller's env happened to carry.
        match req.tty {
            Some(size) => cmd.env(crate::build_log::TTY_ENV, size.to_string()),
            None => cmd.env_remove(crate::build_log::TTY_ENV),
        };
        // Own process group: a cancel's SIGINT reaches docker and git under
        // it, and nothing aimed at the daemon's group reaches it.
        std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
        let child = match cmd.spawn() {
            Ok(child) => child,
            Err(e) => {
                let _ = std::fs::remove_file(&out.path);
                let _ = std::fs::remove_file(&err.path);
                return Err(e).with_context(|| format!("cannot run {}", Path::new(&program).display()));
            }
        };
        let pid = child.id();
        let mut running = Running { child, pid, out, err };
        running.out.rename(&runner.spool.join(format!("{pid}.out")));
        running.err.rename(&runner.spool.join(format!("{pid}.err")));
        Ok(running)
    }

    /// Send what both files gained, as `output`. An error: the client is gone.
    fn pump(&mut self, request: Option<u64>, peer: &dyn Peer) -> io::Result<()> {
        self.out.pump("stdout", request, peer)?;
        self.err.pump("stderr", request, peer)
    }

    /// Send the held-back bytes too (the child is done).
    fn flush(&mut self, request: Option<u64>, peer: &dyn Peer) -> io::Result<()> {
        for (spool, stream) in [(&mut self.out, "stdout"), (&mut self.err, "stderr")] {
            if !spool.held.is_empty() {
                let data = std::mem::take(&mut spool.held);
                peer.notify("output", output_params(request, stream, &String::from_utf8_lossy(&data)))?;
            }
        }
        Ok(())
    }

    /// The client is gone (hung up, or its writes fail): SIGINT the group
    /// (the verb rolls back) on a plain hang-up, unless the daemon is
    /// draining; otherwise the verb runs on. Either way it's reaped off this
    /// thread.
    fn gone(self, peer: &dyn Peer, left: Left, table: Arc<InFlight>, label: String, log: fn(&str)) -> Outcome {
        if peer.draining() {
            log(&format!("{label}: the daemon is exiting, left running"));
        } else if left == Left::Slow {
            log(&format!("{label}: client stopped reading, connection cut, left running"));
        } else if left == Left::Detached {
            log(&format!("{label}: detached client left before the answer, left running"));
        } else {
            // The child leads its own group and isn't reaped yet, so its
            // pid can't have been reused.
            match crate::commands::run::cancel::interrupt(self.pid) {
                Ok(()) => log(&format!("{label}: client hung up, SIGINT sent")),
                Err(e) => log(&format!("{label}: client hung up, {e}")),
            }
        }
        self.reap_later(table, label, log);
        Outcome::Gone
    }

    /// Hand the child to a thread that reaps it and cleans up, so the
    /// connection is free (a detached answer) or can close.
    fn reap_later(self, table: Arc<InFlight>, label: String, log: fn(&str)) {
        type Slot = Mutex<Option<(Running, Arc<InFlight>, String)>>;
        fn reap(slot: &Slot, log: fn(&str)) {
            let taken = slot.lock().unwrap_or_else(|e| e.into_inner()).take();
            if let Some((mut running, table, label)) = taken {
                let status = running.child.wait();
                running.finish(&table);
                match status {
                    Ok(status) => log(&format!("{label} exited {}", exit_code(status))),
                    Err(e) => log(&format!("{label}: cannot wait: {e}")),
                }
            }
        }
        let name = format!("serve-verb-{}", self.pid);
        let slot: Arc<Slot> = Arc::new(Mutex::new(Some((self, table, label))));
        let theirs = Arc::clone(&slot);
        if let Err(e) = std::thread::Builder::new().name(name).spawn(move || reap(&theirs, log)) {
            // Never leave a zombie and a holder behind: wait here instead.
            log(&format!("cannot start a reaper thread ({e}), waiting inline"));
            reap(&slot, log);
        }
    }

    /// The exit is reported (or nobody is left to report it to): the spool
    /// files and the table entry go.
    fn finish(&mut self, table: &InFlight) {
        let _ = std::fs::remove_file(&self.out.path);
        let _ = std::fs::remove_file(&self.err.path);
        table.remove(self.pid);
    }
}

impl Spool {
    /// The writable file for the child and the read side, 0600: verb output
    /// can carry secrets.
    fn create(path: &Path, keep_tail: bool) -> anyhow::Result<(File, Spool)> {
        use std::os::unix::fs::OpenOptionsExt;
        let write = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(path)
            .with_context(|| format!("cannot create {}", path.display()))?;
        let file = File::open(path).with_context(|| format!("cannot open {}", path.display()))?;
        Ok((write, Spool { path: path.to_path_buf(), file, held: Vec::new(), tail: Vec::new(), keep_tail }))
    }

    /// Best effort: an unrenamed file still works (the fds stay valid), it
    /// just isn't findable by pid.
    fn rename(&mut self, to: &Path) {
        if std::fs::rename(&self.path, to).is_ok() {
            self.path = to.to_path_buf();
        }
    }

    fn pump(&mut self, stream: &str, request: Option<u64>, peer: &dyn Peer) -> io::Result<()> {
        let mut buf = vec![0u8; CHUNK];
        loop {
            let n = match self.file.read(&mut buf) {
                Ok(0) => return Ok(()),
                Ok(n) => n,
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                // An unreadable spool loses output, not the verb.
                Err(_) => return Ok(()),
            };
            self.held.extend_from_slice(&buf[..n]);
            let cut = complete_utf8(&self.held);
            if cut == 0 {
                continue;
            }
            let data: Vec<u8> = self.held.drain(..cut).collect();
            if self.keep_tail {
                self.tail.extend_from_slice(&data);
                let over = self.tail.len().saturating_sub(ERR_TAIL);
                self.tail.drain(..over);
            }
            peer.notify("output", output_params(request, stream, &String::from_utf8_lossy(&data)))?;
        }
    }
}

/// How much of `buf` to send now: all of it but a trailing UTF-8 sequence
/// the read cut short, so a character split across reads isn't mangled.
/// Invalid bytes aren't held (the lossy decode replaces them).
fn complete_utf8(buf: &[u8]) -> usize {
    let len = buf.len();
    for back in 1..=len.min(3) {
        let b = buf[len - back];
        if b & 0xC0 == 0x80 {
            continue; // a continuation byte: look further back for the lead
        }
        let need = match b {
            0xF0.. => 4,
            0xE0.. => 3,
            0xC0.. => 2,
            _ => 1,
        };
        return if need > back { len - back } else { len };
    }
    len
}

/// The verb's subprocess tracked through `state.toml`: every instance whose
/// `progress.pid` is the child's, and the phase last sent for each.
struct Tracker {
    pid: u32,
    /// The instances before the spawn (for [`Tracker::added`]).
    before: BTreeSet<String>,
    sent: BTreeMap<String, String>,
    /// The first instance seen with the child's pid: the verb's instance.
    instance: Option<String>,
}

impl Tracker {
    fn new(pid: u32, before: BTreeSet<String>) -> Self {
        Self { pid, before, sent: BTreeMap::new(), instance: None }
    }

    /// The `(instance, phase)` changes since the last call; `phase` is the
    /// `PhaseView` label, or `failed`. `view` is injected to keep it pure.
    fn observe(&mut self, state: &State, view: impl Fn(&Progress) -> PhaseView) -> Vec<(String, String)> {
        let mut changes = Vec::new();
        for (key, info) in &state.instances {
            let Some(progress) = info.progress.as_ref().filter(|p| p.pid == self.pid) else { continue };
            let phase = match view(progress) {
                PhaseView::InFlight(label) => label,
                PhaseView::Failed { .. } => "failed".to_string(),
            };
            self.instance.get_or_insert_with(|| key.clone());
            if self.sent.get(key) != Some(&phase) {
                self.sent.insert(key.clone(), phase.clone());
                changes.push((key.clone(), phase));
            }
        }
        changes
    }

    /// The one instance added since the spawn: a `run` that went from start
    /// to ready between two polls.
    fn added(&self, state: &State) -> Option<String> {
        let mut new = state.instances.keys().filter(|k| !self.before.contains(*k));
        let first = new.next()?;
        new.next().is_none().then(|| first.clone())
    }
}

/// How the client left before the answer; only [`Left::HungUp`] cancels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Left {
    HungUp,
    /// It stopped reading for the write timeout: a paused `devsandbox run |
    /// less` mustn't roll a build back. Its connection is cut anyway (a
    /// timed-out write may have left half a line).
    Slow,
    /// A `detach` request: hang-up = cancel unless detached
    /// (docs/architecture/daemon/verbs.md, *Detach and hang-up*), so a
    /// dashboard quit right after `r` doesn't roll its build back, nor
    /// interrupt its `stop`/`rm`.
    Detached,
}

impl Left {
    /// After a failed write to the client.
    fn after_write(e: &io::Error, detach: bool) -> Left {
        match e.kind() {
            io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut => Left::Slow,
            _ if detach => Left::Detached,
            _ => Left::HungUp,
        }
    }
}

/// The `exit` of a `failed`: the code, or 128 + the signal, as shells say.
fn exit_code(status: ExitStatus) -> i32 {
    use std::os::unix::process::ExitStatusExt;
    status.code().unwrap_or_else(|| 128 + status.signal().unwrap_or(0))
}

/// A failed verb's message from its stderr: `main`'s last `Error: …` line
/// without the prefix, its `Caused by:` chain joined as `{:#}` would. Else
/// the last non-empty line (a panic, a signal).
fn error_message(stderr: &str) -> Option<String> {
    let lines: Vec<&str> = stderr.lines().collect();
    let Some(at) = lines.iter().rposition(|l| l.starts_with("Error: ") || l.starts_with("error: ")) else {
        return lines.iter().map(|l| l.trim()).rfind(|l| !l.is_empty()).map(str::to_string);
    };
    let mut message = lines[at]["Error: ".len()..].trim().to_string();
    let rest = &lines[at + 1..];
    if let Some(c) = rest.iter().position(|l| l.trim() == "Caused by:") {
        if rest[..c].iter().all(|l| l.trim().is_empty()) {
            for line in rest[c + 1..].iter().map(|l| l.trim()).take_while(|l| !l.is_empty()) {
                // Several causes are numbered (`0: …`), a single one isn't.
                let cause = match line.split_once(": ") {
                    Some((n, cause)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => cause,
                    _ => line,
                };
                message.push_str(": ");
                message.push_str(cause);
            }
        }
    }
    Some(message)
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::serve::daemon::tests::scratch;

    fn env() -> BTreeMap<String, String> {
        // `sh` scripts need a PATH; a real client sends its whole env.
        BTreeMap::from([("PATH".to_string(), std::env::var("PATH").unwrap_or_default())])
    }

    fn req(verb: Verb, detach: bool) -> VerbRequest {
        VerbRequest { root: "/cfg".into(), env: env(), verb, detach, tty: None }
    }

    fn one(name: &str) -> Target {
        Target::One(name.into())
    }

    #[test]
    fn argv_maps_each_verb_to_its_cli_flags() {
        let s = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        let lead = ["--in-process", "-C", "/cfg"];
        let with = |rest: &[&str]| s(&[&lead[..], rest].concat());
        let run = Verb::Run { sandbox: "web".into(), name: None, branch: None, base: None, json: false, reprobe: false };
        assert_eq!(argv(&req(run, false)), with(&["run", "--", "web"]));
        let run = Verb::Run {
            sandbox: "-web".into(),
            name: Some("w2".into()),
            branch: Some("feat/x".into()),
            base: Some("-odd".into()),
            json: true,
            reprobe: true,
        };
        assert_eq!(
            argv(&req(run, true)),
            with(&["run", "--name=w2", "--branch=feat/x", "--base=-odd", "--json", "--reprobe", "--", "-web"])
        );
        assert_eq!(argv(&req(Verb::Rebuild { target: one("w"), force: true, reprobe: false }, false)), with(&["rebuild", "--force", "--", "w"]));
        assert_eq!(
            argv(&req(Verb::Rebuild { target: one("w"), force: false, reprobe: true }, false)),
            with(&["rebuild", "--reprobe", "--", "w"])
        );
        assert_eq!(argv(&req(Verb::Rebuild { target: Target::All, force: false, reprobe: false }, false)), with(&["rebuild", "--all"]));
        assert_eq!(argv(&req(Verb::Start { target: Target::All }, false)), with(&["start", "--all"]));
        assert_eq!(argv(&req(Verb::Stop { target: one("w") }, false)), with(&["stop", "--", "w"]));
        let rm = |delete_branch, force, ask| Verb::Rm { instance: "w".into(), delete_branch, force, ask };
        assert_eq!(argv(&req(rm(None, false, false), false)), with(&["rm", "--", "w"]));
        assert_eq!(argv(&req(rm(Some(true), true, false), false)), with(&["rm", "--delete-branch", "--force", "--", "w"]));
        assert_eq!(argv(&req(rm(Some(false), false, false), false)), with(&["rm", "--keep-branch", "--", "w"]));
        assert_eq!(argv(&req(rm(None, false, true), false)), with(&["rm", "--fail-on-ask", "--", "w"]));
        let svc = Verb::ServicesRebuild { name: "-db".into() };
        assert_eq!(argv(&req(svc, false)), with(&["service", "rebuild", "--", "-db"]));
        assert_eq!(argv(&req(Verb::Gc { force: false }, false)), with(&["gc"]));
        assert_eq!(argv(&req(Verb::Gc { force: true }, false)), with(&["gc", "--force"]));
    }

    /// The argv parses as the CLI's own verb with the request's values, so a
    /// flag rename can't drift.
    #[test]
    fn argv_parses_as_the_cli() {
        use crate::{Cli, Command};
        use clap::Parser;
        let parse = |verb: Verb| {
            let argv = std::iter::once("devsandbox".to_string()).chain(argv(&req(verb, false)));
            let cli = Cli::try_parse_from(argv).unwrap_or_else(|e| panic!("{e}"));
            assert!(cli.in_process);
            assert_eq!(cli.dir, Path::new("/cfg"));
            cli.command.unwrap()
        };
        let run = Verb::Run {
            sandbox: "-web".into(),
            name: Some("w2".into()),
            branch: Some("-b".into()),
            base: Some("origin/main".into()),
            json: true,
            reprobe: true,
        };
        match parse(run) {
            Command::Run { sandbox, name, branch, base, env, dispatcher, json, reprobe, detach, place } => {
                assert_eq!(sandbox.as_deref(), Some("-web"));
                assert_eq!((name.as_deref(), branch.as_deref(), base.as_deref()), (Some("w2"), Some("-b"), Some("origin/main")));
                // The daemon detaches by itself: the subprocess never gets `-d`.
                // Nor `--place`: placement is the daemon's, the subprocess runs here.
                assert!(json && reprobe && env.is_empty() && dispatcher.is_none() && !detach && !place);
            }
            _ => panic!("not run"),
        }
        let run = Verb::Run { sandbox: "web".into(), name: None, branch: None, base: None, json: false, reprobe: false };
        assert!(matches!(parse(run), Command::Run { name: None, branch: None, base: None, json: false, reprobe: false, .. }));
        match parse(Verb::Rebuild { target: one("-x"), force: true, reprobe: true }) {
            Command::Rebuild { name, all, force, reprobe, detach: false } => {
                assert_eq!((name.as_deref(), all, force, reprobe), (Some("-x"), false, true, true))
            }
            _ => panic!("not rebuild"),
        }
        assert!(matches!(
            parse(Verb::Rebuild { target: Target::All, force: false, reprobe: false }),
            Command::Rebuild { name: None, all: true, force: false, reprobe: false, detach: false }
        ));
        assert!(matches!(parse(Verb::Start { target: one("w") }), Command::Start { name: Some(n), all: false, detach: false } if n == "w"));
        assert!(matches!(parse(Verb::Start { target: Target::All }), Command::Start { name: None, all: true, detach: false }));
        assert!(matches!(parse(Verb::Stop { target: one("w") }), Command::Stop { name: Some(n), all: false } if n == "w"));
        assert!(matches!(parse(Verb::Stop { target: Target::All }), Command::Stop { name: None, all: true }));
        for (delete_branch, flags) in [(None, (false, false)), (Some(true), (true, false)), (Some(false), (false, true))] {
            for ask in [false, true] {
                match parse(Verb::Rm { instance: "w".into(), delete_branch, force: true, ask }) {
                    Command::Rm { name, delete_branch, keep_branch, force, fail_on_ask } => assert_eq!(
                        (name.as_str(), (delete_branch, keep_branch), force, fail_on_ask),
                        ("w", flags, true, ask)
                    ),
                    _ => panic!("not rm"),
                }
            }
        }
        match parse(Verb::ServicesRebuild { name: "-db".into() }) {
            Command::Service { cmd: crate::ServiceCommand::Rebuild { name } } => assert_eq!(name, "-db"),
            _ => panic!("not service rebuild"),
        }
        for force in [false, true] {
            assert!(matches!(parse(Verb::Gc { force }), Command::Gc { force: f } if f == force));
        }
    }

    #[test]
    fn params_are_checked() {
        let root = scratch("verbs-params");
        std::fs::create_dir_all(&root).unwrap();
        let code = |method: &str, params: Value| parse(method, params).map(|_| ()).map_err(|e| e.code);
        let r = root.to_str().unwrap();
        assert_eq!(code("stop", json!({"root": r, "env": {}, "instance": "w"})), Ok(()));
        assert_eq!(code("stop", json!({"root": r, "env": {}, "all": true})), Ok(()));
        assert_eq!(code("stop", json!({"root": "rel", "env": {}, "all": true})), Err("invalid"));
        assert_eq!(code("stop", json!({"root": "/nonexistent/dsv", "env": {}, "all": true})), Err("not-found"));
        // Never the daemon's env.
        assert_eq!(code("stop", json!({"root": r, "all": true})), Err("invalid"));
        assert_eq!(code("stop", json!({"root": r, "env": {"A": 1}, "all": true})), Err("invalid"));
        assert_eq!(code("stop", json!({"root": r, "env": {"A=B": "x"}, "all": true})), Err("invalid"));
        assert_eq!(code("stop", json!({"root": r, "env": {}})), Err("invalid"));
        assert_eq!(code("rebuild", json!({"root": r, "env": {}, "instance": "w", "all": true})), Err("invalid"));
        assert_eq!(code("run", json!({"root": r, "env": {}})), Err("invalid"));
        assert_eq!(code("rm", json!({"root": r, "env": {}})), Err("invalid"));
        let p = parse("rm", json!({"root": r, "env": {}, "instance": "w", "deleteBranch": false})).unwrap();
        assert_eq!(p.verb, Verb::Rm { instance: "w".into(), delete_branch: Some(false), force: false, ask: false });
        let p = parse("rm", json!({"root": r, "env": {}, "instance": "w", "ask": true})).unwrap();
        assert_eq!(p.verb, Verb::Rm { instance: "w".into(), delete_branch: None, force: false, ask: true });
        let p = parse("start", json!({"root": r, "env": {"X": "1"}, "instance": "w", "detach": true})).unwrap();
        assert!(p.detach && p.env["X"] == "1");
        assert!(is_verb("services.rebuild"));
        let p = parse("services.rebuild", json!({"root": r, "env": {}, "name": "db", "detach": true})).unwrap();
        assert_eq!((p.verb, p.detach), (Verb::ServicesRebuild { name: "db".into() }, true));
        let p = parse("services.rebuild", json!({"root": r, "env": {}, "name": "db"})).unwrap();
        assert!(!p.detach);
        let p = parse("stop", json!({"root": r, "env": {}, "instance": "w", "detach": true})).unwrap();
        assert_eq!((p.verb, p.detach), (Verb::Stop { target: one("w") }, true));
        let p = parse("rm", json!({"root": r, "env": {}, "instance": "w", "ask": true, "detach": true})).unwrap();
        assert!(p.detach && matches!(p.verb, Verb::Rm { ask: true, .. }));
        assert_eq!(code("services.rebuild", json!({"root": r, "env": {}})), Err("invalid"));
        assert_eq!(code("services.rebuild", json!({"root": r, "name": "db"})), Err("invalid"));
        assert!(is_verb("gc"));
        let p = parse("gc", json!({"root": r, "env": {}, "force": true})).unwrap();
        assert_eq!((p.verb, p.detach), (Verb::Gc { force: true }, false));
        assert_eq!(parse("gc", json!({"root": r, "env": {}})).unwrap().verb, Verb::Gc { force: false });
        assert_eq!(code("gc", json!({"root": r})), Err("invalid"));
        assert_eq!(code("gc", json!({"env": {}})), Err("invalid"));
        // `tty`: the build verbs', checked.
        let size = TtySize { cols: 100, rows: 30 };
        let tty = |method: &str, extra: Value| {
            let mut params = json!({"root": r, "env": {}, "instance": "w", "sandbox": "web"});
            params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
            parse(method, params).map(|p| p.tty).map_err(|e| e.code)
        };
        for method in ["run", "rebuild", "start"] {
            assert_eq!(tty(method, json!({"tty": {"cols": 100, "rows": 30}})), Ok(Some(size)), "{method}");
            assert_eq!(tty(method, json!({})), Ok(None), "{method}");
            assert_eq!(tty(method, json!({"tty": null})), Ok(None), "{method}");
            for bad in [json!({"cols": 0, "rows": 30}), json!({"cols": 100, "rows": 1001}), json!({"cols": 100}), json!("100x30")] {
                assert_eq!(tty(method, json!({ "tty": bad })), Err("invalid"), "{method} {bad}");
            }
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn detach_answers_at_registration_or_spawn() {
        let run = Verb::Run { sandbox: "web".into(), name: None, branch: None, base: None, json: false, reprobe: false };
        assert_eq!(detach_at(&req(run.clone(), false)), DetachAt::Never);
        assert_eq!(detach_at(&req(run, true)), DetachAt::Registered);
        assert_eq!(detach_at(&req(Verb::Rebuild { target: one("w"), force: false, reprobe: false }, true)), DetachAt::Registered);
        assert_eq!(detach_at(&req(Verb::Rebuild { target: Target::All, force: false, reprobe: false }, true)), DetachAt::Spawn);
        assert_eq!(detach_at(&req(Verb::Start { target: one("w") }, true)), DetachAt::Spawn);
        // Held verbs: `detach` only spares them a hang-up's cancel.
        assert_eq!(detach_at(&req(Verb::ServicesRebuild { name: "db".into() }, true)), DetachAt::Never);
        assert_eq!(detach_at(&req(Verb::Gc { force: false }, true)), DetachAt::Never);
        assert_eq!(detach_at(&req(Verb::Stop { target: one("w") }, true)), DetachAt::Never);
        assert_eq!(detach_at(&req(Verb::Stop { target: Target::All }, true)), DetachAt::Never);
        let rm = Verb::Rm { instance: "w".into(), delete_branch: None, force: false, ask: true };
        assert_eq!(detach_at(&req(rm, true)), DetachAt::Never);
    }

    #[test]
    fn utf8_split_across_reads_is_held_back() {
        let euro = "€".as_bytes(); // 3 bytes
        assert_eq!(complete_utf8(b"abc"), 3);
        assert_eq!(complete_utf8(&[b'a', euro[0]]), 1);
        assert_eq!(complete_utf8(&[b'a', euro[0], euro[1]]), 1);
        assert_eq!(complete_utf8(&[b'a', euro[0], euro[1], euro[2]]), 4);
        // Garbage isn't held forever.
        assert_eq!(complete_utf8(&[0x80, 0x80, 0x80, 0x80]), 4);
        assert_eq!(complete_utf8(&[]), 0);
    }

    #[test]
    fn error_message_is_mains_error_with_its_causes() {
        assert_eq!(error_message("warning: x\nError: `web` cancelled: rolled back\n").as_deref(), Some("`web` cancelled: rolled back"));
        let chain = "building\nError: cannot start web\n\nCaused by:\n    0: docker run failed\n    1: exit 125\n";
        assert_eq!(error_message(chain).as_deref(), Some("cannot start web: docker run failed: exit 125"));
        let single = "Error: cannot start web\n\nCaused by:\n    no space left\n";
        assert_eq!(error_message(single).as_deref(), Some("cannot start web: no space left"));
        assert_eq!(error_message("thread 'main' panicked\n\n").as_deref(), Some("thread 'main' panicked"));
        assert_eq!(error_message(" \n"), None);
    }

    fn state(toml: &str) -> State {
        toml::from_str(toml).unwrap()
    }

    fn instance_toml(key: &str, progress: &str) -> String {
        format!(
            "[instance.{key}]\nsandbox = \"web\"\ncontainer = \"devsandbox-{key}\"\nfolder = \"/w\"\nworkspace = \"/w\"\ncreated_unix = 1\n{progress}"
        )
    }

    #[test]
    fn tracker_reports_phase_changes_of_the_childs_instances() {
        let mut t = Tracker::new(42, BTreeSet::from(["old".to_string()]));
        let alive = |p: &Progress| p.view(|_| true, None);
        let progress = |key: &str, phase: &str, pid: u32| {
            instance_toml(key, &format!("[instance.{key}.progress]\nphase = \"{phase}\"\npid = {pid}\n"))
        };
        let s = state(&format!("{}{}", progress("web-2", "building", 42), progress("other", "building", 7)));
        assert_eq!(t.observe(&s, alive), vec![("web-2".to_string(), "building".to_string())]);
        assert_eq!(t.observe(&s, alive), vec![], "unchanged: nothing");
        assert_eq!(t.instance.as_deref(), Some("web-2"));
        let s = state(&progress("web-2", "failed", 42));
        assert_eq!(t.observe(&s, alive), vec![("web-2".to_string(), "failed".to_string())]);
        // A dead pid's in-flight phase reads as failed (interrupted).
        let mut t = Tracker::new(42, BTreeSet::new());
        let dead = |p: &Progress| p.view(|_| false, None);
        assert_eq!(t.observe(&state(&progress("w", "creating", 42)), dead), vec![("w".to_string(), "failed".to_string())]);

        let t = Tracker::new(42, BTreeSet::from(["old".to_string()]));
        assert_eq!(t.added(&state(&format!("{}{}", instance_toml("old", ""), instance_toml("new", "")))).as_deref(), Some("new"));
        assert_eq!(t.added(&state(&format!("{}{}", instance_toml("a", ""), instance_toml("b", "")))), None, "two: unknown");
    }

    /// A fake connection: records notifications, hangs up on cue.
    #[derive(Default)]
    pub(crate) struct FakePeer {
        notes: Mutex<Vec<(String, Value)>>,
        hang_up_at: Mutex<Option<Instant>>,
        draining: std::sync::atomic::AtomicBool,
    }

    impl Peer for FakePeer {
        fn notify(&self, method: &str, params: Value) -> io::Result<()> {
            self.notes.lock().unwrap().push((method.to_string(), params));
            Ok(())
        }

        fn hung_up(&self, tick: Duration) -> bool {
            if self.hang_up_at.lock().unwrap().is_some_and(|at| Instant::now() >= at) {
                return true;
            }
            std::thread::sleep(tick);
            false
        }

        fn draining(&self) -> bool {
            self.draining.load(Ordering::SeqCst)
        }
    }

    impl FakePeer {
        fn output(&self, stream: &str) -> String {
            let notes = self.notes.lock().unwrap();
            notes
                .iter()
                .filter(|(m, p)| m == "output" && p["stream"] == stream)
                .map(|(_, p)| p["data"].as_str().unwrap().to_string())
                .collect()
        }

        fn progress(&self) -> Vec<(String, String)> {
            let notes = self.notes.lock().unwrap();
            notes
                .iter()
                .filter(|(m, _)| m == "progress")
                .map(|(_, p)| (p["instance"].as_str().unwrap().into(), p["phase"].as_str().unwrap().into()))
                .collect()
        }
    }

    /// A runner whose verbs are `script` (`sh -c`, the argv as `$1…`), with
    /// a scratch spool and state; `$STATE` and `$DIR` point at them.
    pub(crate) fn script_runner(tag: &str, script: &str) -> (Runner, PathBuf) {
        let dir = scratch(&format!("verbs-{tag}"));
        std::fs::create_dir_all(&dir).unwrap();
        let script = format!("STATE='{}'; DIR='{}'; {script}", dir.join("state.toml").display(), dir.display());
        let runner = Runner {
            program: vec!["/bin/sh".into(), "-c".into(), script.into(), "sh".into()],
            spool: dir.join("spool"),
            state: dir.join("state.toml"),
        };
        (runner, dir)
    }

    #[test]
    fn spool_names_are_verbs_temps_or_not_ours() {
        assert_eq!(spool_name("123.out"), Some(SpoolName::Verb(123)));
        assert_eq!(spool_name("123.err"), Some(SpoolName::Verb(123)));
        assert_eq!(spool_name(".77-0.out.tmp"), Some(SpoolName::Temp(77)));
        assert_eq!(spool_name(".77-12.err.tmp"), Some(SpoolName::Temp(77)));
        for other in ["123.log", "x.out", ".out", "+1.out", "123.out.tmp", ".77.out.tmp", ".77-x.out.tmp", "notes"] {
            assert_eq!(spool_name(other), None, "{other}");
        }
    }

    #[test]
    fn the_sweep_keeps_live_verbs_and_drops_the_dead() {
        let dir = scratch("verbs-sweep");
        std::fs::create_dir_all(&dir).unwrap();
        for name in ["10.out", "10.err", "20.out", "20.err", ".30-0.out.tmp", ".40-1.err.tmp", "notes"] {
            std::fs::write(dir.join(name), "").unwrap();
        }
        let live = sweep(&dir, &|pid| pid == 10 || pid == 30, |_| {});
        assert_eq!(live, BTreeSet::from([10]));
        let mut left: Vec<_> =
            std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
        left.sort();
        assert_eq!(left, [".30-0.out.tmp", "10.err", "10.out", "notes"]);
        // A missing dir: nothing to adopt.
        assert!(sweep(&dir.join("nope"), &|_| true, |_| {}).is_empty());
        let _ = std::fs::remove_dir_all(&dir);
    }

    fn wait_for(what: &str, f: impl Fn() -> bool) {
        let deadline = Instant::now() + Duration::from_secs(5);
        while !f() {
            assert!(Instant::now() < deadline, "timed out waiting for {what}");
            std::thread::sleep(Duration::from_millis(20));
        }
    }

    fn stop(name: &str) -> VerbRequest {
        req(Verb::Stop { target: one(name) }, false)
    }

    #[test]
    fn a_verb_streams_its_output_and_answers_its_exit() {
        let (runner, dir) = script_runner("ok", r#"echo "args: $*"; echo e1 >&2; printf 'o2\n'; printf 'e2 €\n' >&2"#);
        let table = Arc::new(InFlight::default());
        let peer = FakePeer::default();
        let out = serve(&stop("web"), Some(7), &runner, &table, &peer, "test", |_| {});
        // No such instance in the (empty) state: unknown.
        assert_eq!(out.answer().unwrap(), json!({"instance": null, "exit": 0}));
        assert_eq!(peer.output("stdout"), "args: --in-process -C /cfg stop -- web\no2\n");
        assert_eq!(peer.output("stderr"), "e1\ne2 €\n");
        assert!(peer.notes.lock().unwrap().iter().all(|(_, p)| p["request"] == 7));
        assert_eq!(table.len(), 0);
        // Spool files are gone once the exit is reported.
        assert_eq!(std::fs::read_dir(&runner.spool).unwrap().count(), 0);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The request's `tty` reaches the verb as `DEVSANDBOX_TTY`, and only
    /// the request's: none, and the caller's env can't slip one in.
    #[test]
    fn a_tty_request_runs_its_verb_with_the_size_in_the_env() {
        let (runner, dir) = script_runner("tty", r#"echo "tty=${DEVSANDBOX_TTY-unset}""#);
        let table = Arc::new(InFlight::default());
        let rebuild = Verb::Rebuild { target: one("web"), force: false, reprobe: false };
        let mut sized = req(rebuild.clone(), false);
        sized.tty = Some(TtySize { cols: 100, rows: 30 });
        let mut plain = req(rebuild, false);
        plain.env.insert(crate::build_log::TTY_ENV.into(), "9x9".into());
        for (request, seen) in [(sized, "tty=100x30\n"), (plain, "tty=unset\n")] {
            let peer = FakePeer::default();
            let out = serve(&request, None, &runner, &table, &peer, "test", |_| {});
            assert_eq!(out.answer().unwrap()["exit"], 0);
            assert_eq!(peer.output("stdout"), seen);
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// No instance verb: even an instance named like the service isn't
    /// what the answer names, on success or failure.
    #[test]
    fn services_rebuild_answers_no_instance() {
        let (runner, dir) = script_runner("svc", r#"echo "args: $*"; [ "$7" = db ] || { echo 'Error: no service' >&2; exit 2; }"#);
        std::fs::write(&runner.state, instance_toml("db", "")).unwrap();
        let svc = |name: &str| req(Verb::ServicesRebuild { name: name.into() }, false);
        let peer = FakePeer::default();
        let out = serve(&svc("db"), Some(1), &runner, &Arc::default(), &peer, "test", |_| {});
        assert_eq!(out.answer().unwrap(), json!({"instance": null, "exit": 0}));
        assert_eq!(peer.output("stdout"), "args: --in-process -C /cfg service rebuild -- db\n");
        let f = serve(&svc("nope"), Some(2), &runner, &Arc::default(), &peer, "test", |_| {}).answer().unwrap_err();
        assert_eq!((f.code, f.message.as_str(), f.data), ("failed", "no service", Some(json!({"exit": 2, "instance": null}))));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn env_is_the_requests_only() {
        let (runner, dir) = script_runner("env", r#"echo "${HOME:-nohome} $GIT_TERMINAL_PROMPT $MINE""#);
        let mut r = stop("web");
        r.env.insert("MINE".into(), "mine".into());
        let peer = FakePeer::default();
        serve(&r, None, &runner, &Arc::default(), &peer, "test", |_| {}).answer().unwrap();
        assert_eq!(peer.output("stdout"), "nohome 0 mine\n");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_failing_verb_answers_failed_with_its_exit_and_error() {
        let (runner, dir) = script_runner(
            "fail",
            &format!("printf '{}' > \"$STATE\"; echo 'Error: no space' >&2; exit 3", instance_toml("web-2", "")),
        );
        let peer = FakePeer::default();
        let out = serve(&stop("web"), Some(1), &runner, &Arc::default(), &peer, "test", |_| {});
        let f = out.answer().unwrap_err();
        assert_eq!((f.code, f.message.as_str()), ("failed", "no space"));
        assert_eq!(f.data, Some(json!({"exit": 3, "instance": null})));
        // A name that resolves (sandbox `web` → its one instance) is named.
        let out = serve(&stop("web"), Some(2), &runner, &Arc::default(), &peer, "test", |_| {});
        assert_eq!(out.answer().unwrap_err().data, Some(json!({"exit": 3, "instance": "web-2"})));
        // Killed by a signal: 128 + it.
        let (runner, dir2) = script_runner("killed", "kill -9 $$");
        let f = serve(&stop("x"), None, &runner, &Arc::default(), &peer, "test", |_| {}).answer().unwrap_err();
        assert_eq!(f.data.unwrap()["exit"], 137);
        let _ = std::fs::remove_dir_all(&dir);
        let _ = std::fs::remove_dir_all(&dir2);
    }

    #[test]
    fn an_rm_that_must_ask_answers_confirm_with_the_question() {
        let q = "delete branch `b`? it has commits not on its remote";
        let (runner, dir) = script_runner("confirm", &format!("echo 'Error: {q}' >&2; exit 3"));
        let rm = |ask| req(Verb::Rm { instance: "w".into(), delete_branch: None, force: false, ask }, false);
        let peer = FakePeer::default();
        let f = serve(&rm(true), None, &runner, &Arc::default(), &peer, "test", |_| {}).answer().unwrap_err();
        assert_eq!((f.code, f.message.as_str(), f.data), ("confirm", q, None));
        // Not asked for: exit 3 is any failure.
        let f = serve(&rm(false), None, &runner, &Arc::default(), &peer, "test", |_| {}).answer().unwrap_err();
        assert_eq!((f.code, f.data), ("failed", Some(json!({"exit": 3, "instance": null}))));
        let (runner, dir2) = script_runner("confirm-other", "echo 'Error: boom' >&2; exit 1");
        let f = serve(&rm(true), None, &runner, &Arc::default(), &peer, "test", |_| {}).answer().unwrap_err();
        assert_eq!((f.code, f.message.as_str()), ("failed", "boom"));
        let _ = std::fs::remove_dir_all(&dir);
        let _ = std::fs::remove_dir_all(&dir2);
    }

    /// `$` is the child's pid: the script records itself as the verb does.
    fn phase_script(steps: &[&str]) -> String {
        let mut script = String::new();
        for phase in steps {
            let progress = match *phase {
                "ready" => String::new(),
                phase => format!("[instance.web-2.progress]\nphase = \"{phase}\"\npid = %s\n"),
            };
            let toml = instance_toml("web-2", &progress);
            script.push_str(&format!("printf '{toml}' \"$$\" > \"$STATE.tmp\"; mv \"$STATE.tmp\" \"$STATE\"; sleep 0.4; "));
        }
        script
    }

    #[test]
    fn progress_follows_the_childs_instance() {
        let (runner, dir) = script_runner("progress", &phase_script(&["preparing", "building", "ready"]));
        let run = Verb::Run { sandbox: "web".into(), name: None, branch: None, base: None, json: false, reprobe: false };
        let peer = FakePeer::default();
        let out = serve(&req(run, false), Some(3), &runner, &Arc::default(), &peer, "test", |_| {});
        assert_eq!(out.answer().unwrap(), json!({"instance": "web-2", "exit": 0}));
        assert_eq!(
            peer.progress(),
            [("web-2".to_string(), "preparing".to_string()), ("web-2".to_string(), "building".to_string())]
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn detach_answers_once_registered_and_the_verb_runs_on() {
        let script = format!("{} touch \"$DIR/finished\"", phase_script(&["building", "building", "building", "ready"]));
        let (runner, dir) = script_runner("detach", &script);
        let run = Verb::Run { sandbox: "web".into(), name: None, branch: None, base: None, json: true, reprobe: false };
        let table = Arc::new(InFlight::default());
        let peer = FakePeer::default();
        let started = Instant::now();
        let out = serve(&req(run, true), Some(4), &runner, &table, &peer, "test", |_| {});
        let answer = out.answer().unwrap();
        assert!(started.elapsed() < Duration::from_millis(1000), "{:?}", started.elapsed());
        assert_eq!((&answer["instance"], &answer["detached"]), (&json!("web-2"), &json!(true)));
        assert_eq!(answer["record"]["name"], "web-2");
        assert_eq!(answer["record"]["container"], "devsandbox-web-2");
        // Still a holder until reaped, then cleaned up.
        assert_eq!(table.len(), 1);
        wait_for("the reaper", || table.len() == 0);
        assert!(dir.join("finished").exists());
        assert_eq!(std::fs::read_dir(&runner.spool).unwrap().count(), 0);

        // `start`: right after the spawn.
        let (runner, dir2) = script_runner("detach-start", "sleep 0.5");
        let started = Instant::now();
        let out = serve(&req(Verb::Start { target: Target::All }, true), None, &runner, &table, &peer, "test", |_| {});
        assert_eq!(out.answer().unwrap(), json!({"instance": null, "detached": true}));
        assert!(started.elapsed() < Duration::from_millis(400));
        wait_for("the reaper", || table.len() == 0);
        let _ = std::fs::remove_dir_all(&dir);
        let _ = std::fs::remove_dir_all(&dir2);
    }

    const TRAPPED: &str = r#"trap 'echo int > "$DIR/int"; exit 130' INT; echo ready; sleep 1; touch "$DIR/done""#;

    #[test]
    fn a_hang_up_sigints_the_group() {
        let (runner, dir) = script_runner("hangup", TRAPPED);
        let table = Arc::new(InFlight::default());
        let peer = FakePeer::default();
        *peer.hang_up_at.lock().unwrap() = Some(Instant::now() + Duration::from_millis(300));
        let out = serve(&stop("w"), None, &runner, &table, &peer, "test", |_| {});
        assert!(matches!(out, Outcome::Gone));
        wait_for("the trap", || dir.join("int").exists());
        wait_for("the reaper", || table.len() == 0);
        assert!(!dir.join("done").exists());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_drain_is_not_a_hang_up() {
        let (runner, dir) = script_runner("drain", TRAPPED);
        let table = Arc::new(InFlight::default());
        let peer = FakePeer::default();
        *peer.hang_up_at.lock().unwrap() = Some(Instant::now() + Duration::from_millis(300));
        peer.draining.store(true, Ordering::SeqCst);
        let out = serve(&stop("w"), None, &runner, &table, &peer, "test", |_| {});
        assert!(matches!(out, Outcome::Gone));
        wait_for("the verb", || dir.join("done").exists());
        assert!(!dir.join("int").exists());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn only_a_hang_up_write_error_cancels() {
        use io::ErrorKind::*;
        for kind in [BrokenPipe, ConnectionReset, NotConnected] {
            assert_eq!(Left::after_write(&kind.into(), false), Left::HungUp, "{kind:?}");
            assert_eq!(Left::after_write(&kind.into(), true), Left::Detached, "{kind:?}");
        }
        // The write timeout: a client that stopped reading (a paused pager).
        for kind in [WouldBlock, TimedOut] {
            assert_eq!(Left::after_write(&kind.into(), false), Left::Slow, "{kind:?}");
        }
    }

    #[test]
    fn a_detached_request_survives_a_hang_up_before_its_answer() {
        let (runner, dir) = script_runner("detach-hangup", TRAPPED);
        let table = Arc::new(InFlight::default());
        let peer = FakePeer::default();
        *peer.hang_up_at.lock().unwrap() = Some(Instant::now() + Duration::from_millis(300));
        // `rebuild <one>` detaches only once registered, which the script never does.
        let out = serve(&req(Verb::Rebuild { target: one("w"), force: false, reprobe: false }, true), None, &runner, &table, &peer, "test", |_| {});
        assert!(matches!(out, Outcome::Gone));
        wait_for("the verb", || dir.join("done").exists());
        assert!(!dir.join("int").exists());
        let _ = std::fs::remove_dir_all(&dir);
    }

    impl Outcome {
        fn answer(self) -> Result<Value, Failure> {
            match self {
                Outcome::Answer(a) => a,
                Outcome::Gone => panic!("no answer"),
            }
        }
    }

    /// Every verb's params, results and notifications match `index.d.ts`.
    #[test]
    fn npm_typings_match_the_verb_wire() {
        use crate::serve::dts::{assert_matches, prop_type};
        let v = |x: &dyn erased::Ser| x.value();
        let (root, e) = (PathBuf::from("/cfg"), BTreeMap::new());
        let run = RunParams {
            root: root.clone(),
            env: e.clone(),
            sandbox: "web".into(),
            name: None,
            branch: None,
            base: None,
            json: true,
            reprobe: true,
            detach: true,
            tty: Some(TtySize { cols: 100, rows: 30 }),
            place: true,
        };
        let rebuild = RebuildParams {
            root: root.clone(),
            env: e.clone(),
            instance: None,
            all: true,
            force: false,
            reprobe: false,
            detach: false,
            tty: None,
        };
        let start = StartParams { root: root.clone(), env: e.clone(), instance: None, all: true, detach: false, tty: None };
        let stop = StopParams { root: root.clone(), env: e.clone(), instance: None, all: true, detach: true };
        let rm = RmParams {
            root: root.clone(),
            env: e.clone(),
            instance: "w".into(),
            delete_branch: None,
            force: false,
            ask: true,
            detach: true,
        };
        let services_rebuild = ServicesRebuildParams { root: root.clone(), env: e.clone(), name: "db".into(), detach: true };
        let gc = GcParams { root, env: e, force: true, detach: true };
        for (iface, value) in [
            ("RunParams", v(&run)),
            ("RebuildParams", v(&rebuild)),
            ("StartParams", v(&start)),
            ("StopParams", v(&stop)),
            ("RmParams", v(&rm)),
            ("ServicesRebuildParams", v(&services_rebuild)),
            ("GcParams", v(&gc)),
            ("TtySize", v(&TtySize { cols: 100, rows: 30 })),
            ("VerbResult", done_result(Some("w"))),
            ("VerbDetached", detached_result(Some("w"), Some(json!({})))),
            ("VerbFailedData", failed_data(1, None)),
            ("VerbOutput", output_params(Some(1), "stdout", "x")),
            ("VerbProgress", progress_params(Some(1), "w", "building")),
        ] {
            assert_matches(iface, &value);
        }
        assert_eq!(prop_type("VerbDetached", "record").as_deref(), Some("RunRecord"));
        for iface in ["RunParams", "RebuildParams", "StartParams"] {
            assert_eq!(prop_type(iface, "tty").as_deref(), Some("TtySize | null"), "{iface}");
        }
        assert!(prop_type("ApiMethods", "services.rebuild").is_some_and(|t| t.contains("result: VerbResult ")));
        assert!(prop_type("ApiMethods", "gc").is_some_and(|t| t.contains("params: GcParams") && t.contains("result: VerbResult ")));
        for method in ["run", "rebuild", "start", "stop", "rm"] {
            assert!(prop_type("ApiMethods", method).is_some(), "ApiMethods lacks `{method}`");
        }
        assert_eq!(prop_type("ApiEvents", "output").as_deref(), Some("VerbOutput"));
        assert_eq!(prop_type("ApiEvents", "progress").as_deref(), Some("VerbProgress"));
    }

    mod erased {
        pub trait Ser {
            fn value(&self) -> serde_json::Value;
        }
        impl<T: serde::Serialize> Ser for T {
            fn value(&self) -> serde_json::Value {
                serde_json::to_value(self).unwrap()
            }
        }
    }
}