sandlock-cli 0.9.1

CLI for sandlock process sandbox
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
use anyhow::{anyhow, Result};
use clap::{Parser, Subcommand};
use sandlock_core::profile;
use sandlock_core::sandbox::{parse_timestamp, BranchAction, ByteSize, SandboxBuilder};
use sandlock_core::Sandbox;
use std::path::PathBuf;

#[cfg(all(feature = "profiles", feature = "cow"))]
mod learn;
#[derive(Parser)]
#[command(name = "sandlock", about = "Lightweight process sandbox", version)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Run a command in a sandbox
    Run(RunArgs),
    /// Check kernel feature support
    Check,
    /// List all running sandboxes
    Ps,
    /// Show effective policy for a running sandbox
    Inspect {
        /// Sandbox name (as shown by `sandlock ps`)
        name: String,
        /// Output TOML instead of JSON
        #[arg(long)]
        toml: bool,
    },
    /// Kill a running sandbox by name
    Kill {
        /// Sandbox name (as shown by `sandlock ps`)
        name: String,
    },
    /// Manage profiles
    Profile {
        #[command(subcommand)]
        action: ProfileAction,
    },
    /// Observe a workload and emit a sandlock profile
    Learn(LearnArgs),
}

/// Arguments for the `run` subcommand.
///
/// Sandbox-level flags come from `SandboxBuilder` via `#[clap(flatten)]`.
/// CLI-only flags (profile, timeout, image, etc.) and non-clap-friendly
/// sandbox fields (max_memory, fs_mount, env, gpu, cpu-cores) remain here.
/// GPU visibility for `--gpu`: `all` for every present GPU, or explicit
/// indices like `0,2`. Absence of the flag means no GPU access.
#[derive(Clone, Debug)]
enum GpuSelection {
    All,
    Devices(Vec<u32>),
}

impl std::str::FromStr for GpuSelection {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.eq_ignore_ascii_case("all") {
            return Ok(GpuSelection::All);
        }
        let devices = s
            .split(',')
            .map(|p| {
                let p = p.trim();
                p.parse::<u32>().map_err(|_| {
                    format!("invalid GPU index '{p}'; expected 'all' or indices like 0,2")
                })
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(GpuSelection::Devices(devices))
    }
}

#[derive(clap::Args)]
struct RunArgs {
    // ── Sandbox flags (flattened from SandboxBuilder) ───────────────────────
    #[clap(flatten)]
    sandbox_builder: SandboxBuilder,

    // ── Sandbox-builder fields that need special parsing (not in SandboxBuilder's clap derive) ──
    #[arg(short = 'm', long = "max-memory")]
    max_memory: Option<String>,

    #[arg(long = "max-disk")]
    max_disk: Option<String>,

    #[arg(long)]
    time_start: Option<String>,

    /// Mount a host path inside the sandbox; append :ro for read-only
    /// (e.g. --fs-mount /work:/host/path or --fs-mount /work:/host/path:ro)
    #[arg(long = "fs-mount", value_name = "VIRTUAL:HOST[:ro]")]
    fs_mount: Vec<String>,

    /// COW branch action on normal sandbox exit: commit | abort | keep
    /// (default: commit).
    #[arg(long = "on-exit", value_name = "ACTION")]
    on_exit: Option<String>,

    /// COW branch action on sandbox error: commit | abort | keep
    /// (default: abort).
    #[arg(long = "on-error", value_name = "ACTION")]
    on_error: Option<String>,

    #[arg(long = "env", value_name = "KEY=VALUE")]
    env_vars: Vec<String>,

    /// Report VALUE as a uname field: release, version, sysname, machine or
    /// domainname (e.g. --uname release=8.0.0). Repeatable.
    #[arg(long = "uname", value_name = "FIELD=VALUE")]
    uname: Vec<String>,

    /// CPU cores to pin the sandbox to (e.g. --cpu-cores 0,2,3)
    #[arg(long = "cpu-cores", value_delimiter = ',')]
    cpu_cores: Vec<u32>,

    /// GPUs visible to the sandbox: `all` for every GPU, or indices (e.g. --gpu 0,2)
    #[arg(long = "gpu", value_name = "all|N,N,...")]
    gpu: Option<GpuSelection>,

    // ── CLI-only flags ───────────────────────────────────────────────────────
    #[arg(short = 't', long)]
    timeout: Option<u64>,

    #[arg(short = 'p', long, conflicts_with = "profile_file")]
    profile: Option<String>,

    /// Load a profile directly from a file path (TOML format)
    #[arg(long = "profile-file", value_name = "PATH", conflicts_with = "profile")]
    profile_file: Option<PathBuf>,

    #[arg(long = "status-fd", value_name = "FD")]
    status_fd: Option<i32>,

    /// After the command exits, keep its background jobs running under
    /// supervision until they finish; exit with the command's status
    #[arg(short = 'j', long = "wait-jobs")]
    wait_jobs: bool,

    /// Sandbox name (also exposed as the virtual hostname; auto-generated if omitted)
    #[arg(long)]
    name: Option<String>,

    #[arg(short = 'e', long = "exec-shell", value_name = "CMD")]
    exec_shell: Option<String>,

    /// Use a container image as chroot rootfs, named with skopeo's transport
    /// syntax: `docker://<ref>` (registry), `docker-daemon:<ref>` (local
    /// Docker daemon), `oci:<dir>[:tag]` or `oci-archive:<file>[:tag]`.
    #[arg(long, value_name = "IMAGE")]
    image: Option<String>,

    /// Dry-run: run the command, show filesystem changes, then discard
    #[arg(long)]
    dry_run: bool,

    /// No-supervisor mode: apply Landlock rules + deny-only seccomp filter, then exec directly
    #[arg(long)]
    no_supervisor: bool,

    /// Allow the named protection to degrade silently if the host kernel ABI lacks support.
    /// Repeatable. Accepted values: fs-refer, fs-truncate, net-tcp, fs-ioctl-dev,
    /// signal-scope, abstract-unix-socket-scope.
    #[arg(long = "allow-degraded", value_name = "PROTECTION")]
    allow_degraded: Vec<String>,

    /// Disable the named protection entirely (no rule emitted, no error on missing ABI).
    /// Repeatable. Accepts the same values as --allow-degraded, except fs-refer:
    /// the kernel denies REFER by default even when unhandled, so disabling it
    /// only tightens the sandbox and is rejected.
    #[arg(long = "disable", value_name = "PROTECTION")]
    disable: Vec<String>,

    #[arg(last = true)]
    cmd: Vec<String>,
}

/// Parse a kebab-case protection name into a `Protection` value.
///
/// The canonical names match the Landlock kernel constants
/// (`LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET` → `abstract-unix-socket-scope`,
/// etc.) and are case-insensitive. Accepted: `fs-refer`, `fs-truncate`,
/// `net-tcp`, `fs-ioctl-dev`, `signal-scope`,
/// `abstract-unix-socket-scope`.
fn parse_protection(s: &str) -> Result<sandlock_core::Protection, String> {
    use sandlock_core::Protection;
    match s.to_ascii_lowercase().as_str() {
        "fs-refer" => Ok(Protection::FsRefer),
        "fs-truncate" => Ok(Protection::FsTruncate),
        "net-tcp" => Ok(Protection::NetTcp),
        "fs-ioctl-dev" => Ok(Protection::FsIoctlDev),
        "signal-scope" => Ok(Protection::SignalScope),
        "abstract-unix-socket-scope" => Ok(Protection::AbstractUnixSocketScope),
        other => Err(format!(
            "unknown protection: {} (valid: fs-refer, fs-truncate, net-tcp, fs-ioctl-dev, signal-scope, abstract-unix-socket-scope)",
            other,
        )),
    }
}

#[derive(Subcommand)]
enum ProfileAction {
    /// List available profiles
    List,
    /// Show profile contents
    Show { name: String },
    /// Delete a profile
    Delete { name: String },
}

/// Arguments for the `learn` subcommand.
#[derive(clap::Args)]
struct LearnArgs {
    /// Write observed profile to this file (default: print to stdout)
    #[arg(short = 'o', long, value_name = "PATH")]
    output: Option<PathBuf>,

    /// Union observed rules into an existing profile file and write it back
    #[arg(long, value_name = "PATH")]
    merge: Option<PathBuf>,

    /// Kill the observed process after this many seconds and write a partial profile
    #[arg(long, value_name = "SECS")]
    timeout: Option<u64>,

    /// Collapse directories where N or more files were observed (default N=4 when flag is present)
    #[arg(long, value_name = "N", default_missing_value = "4", num_args = 0..=1)]
    collapse: Option<usize>,

    /// Force collapse of all observed paths under PREFIX to that prefix (repeatable)
    #[arg(long, value_name = "PREFIX")]
    collapse_prefix: Vec<PathBuf>,

    /// Allow --collapse-prefix to target sensitive directories (prints a warning and diff for each)
    #[arg(long, requires = "collapse_prefix")]
    force_sensitive_collapse: bool,

    /// Inject an ephemeral MITM CA into this trust bundle to observe HTTPS.
    /// Enables port 443 interception.
    #[arg(long, value_name = "PATH")]
    http_inject_ca: Vec<PathBuf>,

    /// Additional TCP port to intercept for HTTP/HTTPS learning (repeatable)
    #[arg(long, value_name = "PORT")]
    http_port: Vec<u16>,

    /// Write the ephemeral MITM CA public cert to this path so the workload can trust it
    /// (e.g. NODE_EXTRA_CA_CERTS=<path> or curl --cacert <path>)
    #[arg(long, value_name = "PATH")]
    http_ca_out: Option<PathBuf>,

    /// Set an environment variable for the observed process and record it in the
    /// profile so sandlock run inherits it (repeatable, KEY=VALUE).
    #[arg(long = "env", value_name = "KEY=VALUE")]
    env_vars: Vec<String>,

    /// Command to observe (everything after --)
    #[arg(last = true, required = true)]
    cmd: Vec<String>,
}

#[derive(serde::Serialize)]
struct SandboxStatus {
    exit_code: i32,
    #[serde(skip_serializing_if = "Option::is_none")]
    signal: Option<i32>,
}

#[tokio::main(worker_threads = 2)]
async fn main() -> Result<()> {
    sandlock_core::logging::log_to_stderr();
    let cli = Cli::parse();

    match cli.command {
        Command::Run(args) => {
            let code = run_command(args).await?;
            std::process::exit(code);
        }

        Command::Ps => {
            let names = match sandlock_core::control::list_sandboxes() {
                Ok(n) => n,
                Err(e) => {
                    eprintln!("sandlock: failed to list sandboxes: {}", e);
                    std::process::exit(1);
                }
            };
            if names.is_empty() {
                println!("No running sandboxes.");
            } else {
                println!("NAME                                  PID        UPTIME  STATUS      PORTS                     CMD");
                for name in &names {
                    // The registry's main pid outlives main. A pidfd opened before
                    // the supervisor vouches main is alive names main, and /proc
                    // is trusted only if main is still alive after reading it.
                    let pid = sandlock_core::control::sandbox_pids(name).map(|p| p.child);
                    let main_fd = pid.as_ref().ok().and_then(|&pid| pidfd_open(pid));
                    let (status, ports, pid, uptime, cmd) =
                        match (sandlock_core::control::sandbox_info(name), pid) {
                            (Ok(info), Ok(pid)) if !info.main_exited => {
                                let uptime = proc_uptime(pid);
                                let cmd = proc_cmdline(pid);
                                if main_fd.as_ref().is_some_and(|fd| !pidfd_exited(fd)) {
                                    (
                                        info.mode.unwrap_or_else(|| "running".to_string()),
                                        query_ports(name),
                                        pid.to_string(),
                                        uptime.unwrap_or_else(|| "?".to_string()),
                                        cmd.unwrap_or_else(|| "?".to_string()),
                                    )
                                } else {
                                    main_exited_row(name, info)
                                }
                            }
                            (Ok(info), _) if info.main_exited => main_exited_row(name, info),
                            (info, pid) => (
                                if info.is_ok() {
                                    "running"
                                } else {
                                    "unresponsive"
                                }
                                .to_string(),
                                "?".to_string(),
                                pid.map_or_else(|_| "?".to_string(), |p| p.to_string()),
                                "?".to_string(),
                                "?".to_string(),
                            ),
                        };
                    println!(
                        "{:<32} {:>8}  {:>12}  {:<10}  {:<24}  {}",
                        name, pid, uptime, status, ports, cmd
                    );
                }
            }
        }

        Command::Inspect { name, toml } => {
            if let Err(e) = validate_cli_name(&name) {
                eprintln!("sandlock: {e}");
                std::process::exit(1);
            }
            match sandlock_core::control::send_control_request(
                &name,
                "config",
                serde_json::Value::Object(Default::default()),
            ) {
                Ok(resp) if resp.ok => {
                    if let Some(data) = resp.data {
                        if toml {
                            #[cfg(not(feature = "profiles"))]
                            return Err(anyhow!("TOML output requires the profiles feature"));
                            #[cfg(feature = "profiles")]
                            {
                                // Round-trip through ProfileInput -> TOML.
                                let profile: sandlock_core::ProfileInput =
                                    serde_json::from_value(data)
                                        .map_err(|e| anyhow!("parse config response: {}", e))?;
                                let toml_str = toml::to_string_pretty(&profile)?;
                                println!("{}", toml_str);
                            }
                        } else {
                            let json_str = serde_json::to_string_pretty(&data)?;
                            println!("{}", json_str);
                        }
                    } else {
                        eprintln!("sandlock: empty response from sandbox");
                        std::process::exit(1);
                    }
                }
                Ok(resp) => {
                    eprintln!(
                        "sandlock: inspect error: {}",
                        resp.err.as_deref().unwrap_or("unknown")
                    );
                    std::process::exit(1);
                }
                Err(e) => {
                    eprintln!("sandlock: inspect failed: {}", e);
                    std::process::exit(1);
                }
            }
        }

        Command::Kill { name } => {
            if let Err(e) = validate_cli_name(&name) {
                eprintln!("sandlock: {e}");
                std::process::exit(1);
            }
            if let Err(e) = sandlock_core::control::kill_sandbox(&name) {
                eprintln!("sandlock: kill '{}': {}", name, e);
                std::process::exit(1);
            }
            println!("Killed sandbox '{}'", name);
        }

        Command::Check => {
            println!("Kernel feature support:");
            match sandlock_core::landlock_abi_version() {
                Ok(v) => {
                    println!("  Landlock:       ABI v{}", v);
                    println!(
                        "  Minimum required: ABI v{}",
                        sandlock_core::MIN_LANDLOCK_ABI
                    );
                    if v < sandlock_core::MIN_LANDLOCK_ABI {
                        println!("  Status:         UNSUPPORTED (upgrade kernel)");
                    } else {
                        println!("  Status:         OK");
                    }
                    println!("  Filesystem:     supported (ABI v1+)");
                    println!(
                        "  File truncate:  {}",
                        if v >= 3 {
                            "supported (ABI v3+)"
                        } else {
                            "not supported"
                        }
                    );
                    println!(
                        "  TCP ports:      {}",
                        if v >= 4 {
                            "supported (ABI v4+)"
                        } else {
                            "not supported"
                        }
                    );
                    println!(
                        "  Device ioctl:   {}",
                        if v >= 5 {
                            "supported (ABI v5+)"
                        } else {
                            "not supported"
                        }
                    );
                    println!(
                        "  IPC scoping:    {}",
                        if v >= 6 {
                            "supported (ABI v6+)"
                        } else {
                            "not supported"
                        }
                    );
                    println!(
                        "  Signal scoping: {}",
                        if v >= 6 {
                            "supported (ABI v6+)"
                        } else {
                            "not supported"
                        }
                    );

                    println!();
                    println!("Per-protection availability (host Landlock ABI v{}):", v);
                    for p in sandlock_core::Protection::all() {
                        let available = v >= p.min_abi();
                        let marker = if available {
                            "available"
                        } else {
                            "unavailable"
                        };
                        println!(
                            "  {:<22} requires v{} — {}",
                            format!("{:?}", p),
                            p.min_abi(),
                            marker
                        );
                    }
                }
                Err(e) => {
                    println!("  Landlock: unavailable ({})", e);
                    println!("  Status:   UNSUPPORTED");
                }
            }
            println!("  Platform: {}", std::env::consts::ARCH);
        }

        Command::Learn(args) => {
            #[cfg(all(feature = "profiles", feature = "cow"))]
            learn::run(args).await?;
            #[cfg(not(all(feature = "profiles", feature = "cow")))]
            return Err(anyhow!(
                "learning profiles requires the profiles and cow features"
            ));
        }

        Command::Profile { action } => match action {
            ProfileAction::List => {
                let profiles = profile::list_profiles()?;
                if profiles.is_empty() {
                    println!("No profiles found in {}", profile::profile_dir()?.display());
                } else {
                    for name in profiles {
                        println!("  {}", name);
                    }
                }
            }
            ProfileAction::Show { name } => {
                let path = profile::profile_dir()?.join(format!("{}.toml", name));
                let content = std::fs::read_to_string(&path)?;
                println!("{}", content);
            }
            ProfileAction::Delete { name } => {
                let path = profile::profile_dir()?.join(format!("{}.toml", name));
                std::fs::remove_file(&path)?;
                println!("Deleted profile '{}'", name);
            }
        },
    }

    Ok(())
}

/// Implementation of `sandlock run`.
/// Returns the desired process exit code; the caller does
/// `process::exit`. Calling `process::exit` here would bypass
/// `Sandbox::Drop`, which is where COW commit/abort runs.
async fn run_command(args: RunArgs) -> Result<i32> {
    let pb = &args.sandbox_builder;

    // `--no-supervisor` reaches the same `Sandbox::run` path as everything
    // else; the deny-only filter and skipped supervisor are gated on the
    // sandbox's `no_supervisor` field. Validate flag/profile combinations
    // upfront so users hit the error before any setup happens.
    if args.no_supervisor {
        validate_no_supervisor(&args)?;
    }

    // Hoist the profile load so we don't read+parse twice.
    let (base_from_profile, profile_program_spec) = if let Some(ref name) = args.profile {
        let (base, spec) = profile::load_profile(name)?;
        (Some(base), Some(spec))
    } else if let Some(ref path) = args.profile_file {
        let content = std::fs::read_to_string(path)
            .map_err(|e| anyhow!("failed to read profile file {}: {}", path.display(), e))?;
        let (base, spec) = profile::parse_profile(&content)?;
        (Some(base), Some(spec))
    } else {
        (None, None)
    };

    if args.no_supervisor {
        if let Some(ref base) = base_from_profile {
            validate_no_supervisor_profile(base, &profile_source(&args))?;
        }
    }

    // Save exec+args for the denial hint.
    let profile_hint_cmd: Option<String> = if !args.cmd.is_empty() {
        Some(args.cmd.join(" "))
    } else {
        profile_program_spec.as_ref().and_then(|spec| {
            let exec = spec.exec.as_ref()?.display().to_string();
            let args_str = spec.args.join(" ");
            Some(if args_str.is_empty() {
                exec
            } else {
                format!("{exec} {args_str}")
            })
        })
    };

    // Start from profile or default
    let mut builder = if let Some(base) = base_from_profile {
        // Rebuild builder from loaded profile as base
        let mut b = Sandbox::builder();
        b.fs_readable.extend(base.fs_readable.iter().cloned());
        b.fs_writable.extend(base.fs_writable.iter().cloned());
        for p in &base.fs_denied {
            b = b.fs_deny(p);
        }
        for rule in &base.net_allow {
            b = b.net_allow(sandlock_core::format_net_rule(rule));
        }
        for rule in &base.net_deny {
            b = b.net_deny(sandlock_core::format_net_rule(rule));
        }
        match &base.net_allow_bind {
            sandlock_core::BindPorts::All => b = b.net_allow_bind("*"),
            sandlock_core::BindPorts::Ports(ports) => {
                for p in ports {
                    b = b.net_allow_bind_port(*p);
                }
            }
        }
        for p in &base.net_deny_bind {
            b = b.net_deny_bind_port(*p);
        }
        for rule in &base.http_allow {
            let s = format!("{} {}{}", rule.method, rule.host, rule.path);
            b = b.http_allow(&s);
        }
        for rule in &base.http_deny {
            let s = format!("{} {}{}", rule.method, rule.host, rule.path);
            b = b.http_deny(&s);
        }
        for port in &base.http_ports {
            b = b.http_port(*port);
        }
        if let Some(mem) = base.max_memory {
            b = b.max_memory(mem);
        }
        if let Some(n) = base.max_processes {
            b = b.max_processes(n);
        }
        if let Some(cpu) = base.max_cpu {
            b = b.max_cpu(cpu);
        }
        if let Some(seed) = base.random_seed {
            b = b.random_seed(seed);
        }
        if let Some(n) = base.num_cpus {
            b = b.num_cpus(n);
        }
        b.uname = base.uname.clone();
        if let Some(n) = base.max_open_files {
            b = b.max_open_files(n);
        }
        if let Some(disk) = base.max_disk {
            b = b.max_disk(disk);
        }
        if !base.extra_deny_syscalls.is_empty() {
            b = b.extra_deny_syscalls(base.extra_deny_syscalls.clone());
        }
        if !base.extra_allow_syscalls.is_empty() {
            b = b.extra_allow_syscalls(base.extra_allow_syscalls.clone());
        }
        b = b.clean_env(base.clean_env);
        for (k, v) in &base.env {
            b = b.env_var(k, v);
        }
        if let Some(ref w) = base.workdir {
            b = b.workdir(w);
        }
        if let Some(ref c) = base.cwd {
            b = b.cwd(c);
        }
        // HTTP MITM material
        if let Some(ref ca) = base.http_ca {
            b = b.http_ca(ca);
        }
        if let Some(ref key) = base.http_key {
            b = b.http_key(key);
        }
        for p in &base.http_inject_ca {
            b = b.http_inject_ca(p);
        }
        if let Some(ref out) = base.http_ca_out {
            b = b.http_ca_out(out);
        }
        // Filesystem extras
        if let Some(ref path) = base.chroot {
            b = b.chroot(path);
        }
        if let Some(ref path) = base.fs_storage {
            b = b.fs_storage(path);
        }
        for (virt, host) in &base.fs_mount {
            if base.fs_mount_ro.iter().any(|d| d == virt) {
                b = b.fs_mount_ro(virt, host);
            } else {
                b = b.fs_mount(virt, host);
            }
        }
        b = b.on_exit(base.on_exit.clone());
        b = b.on_error(base.on_error.clone());
        b = b.deterministic_dirs(base.deterministic_dirs);
        // Determinism / process knobs
        b = b.no_randomize_memory(base.no_randomize_memory);
        b = b.no_huge_pages(base.no_huge_pages);
        b = b.no_coredump(base.no_coredump);
        if let Some(t) = base.time_start {
            b = b.time_start(t);
        }
        // Network virtualization
        b = b.port_remap(base.port_remap);
        // Process identity
        if let Some(user) = base.user {
            b = b.user(user.uid, user.gid);
        }
        // Hardware constraints
        if let Some(ref devs) = base.gpu_devices {
            b = b.gpu_devices(devs.clone());
        }
        if let Some(ref cores) = base.cpu_cores {
            b = b.cpu_cores(cores.clone());
        }
        b
    } else {
        Sandbox::builder()
    };

    // CLI overrides — fields from flattened SandboxBuilder
    builder.fs_readable.extend(pb.fs_readable.iter().cloned());
    builder.fs_writable.extend(pb.fs_writable.iter().cloned());
    if let Some(n) = pb.max_processes {
        builder = builder.max_processes(n);
    }
    for spec in &pb.net_allow {
        builder = builder.net_allow(spec);
    }
    for spec in &pb.net_deny {
        builder = builder.net_deny(spec);
    }
    for spec in &pb.net_allow_bind {
        builder = builder.net_allow_bind(spec);
    }
    for spec in &pb.net_deny_bind {
        builder = builder.net_deny_bind(spec);
    }
    if let Some(seed) = pb.random_seed {
        builder = builder.random_seed(seed);
    }
    if pb.clean_env {
        builder = builder.clean_env(true);
    }
    if let Some(n) = pb.num_cpus {
        builder = builder.num_cpus(n);
    }
    if let Some(cpu) = pb.max_cpu {
        builder = builder.max_cpu(cpu);
    }
    if let Some(n) = pb.max_open_files {
        builder = builder.max_open_files(n);
    }
    for p in &pb.fs_denied {
        builder = builder.fs_deny(p);
    }
    if let Some(ref path) = pb.chroot {
        builder = builder.chroot(path);
    }
    if let Some(user) = pb.user {
        builder = builder.user(user.uid, user.gid);
    }
    if let Some(ref path) = pb.workdir {
        builder = builder.workdir(path);
    }
    if let Some(ref path) = pb.cwd {
        builder = builder.cwd(path);
    }
    if let Some(ref path) = pb.fs_storage {
        builder = builder.fs_storage(path);
    }
    if !pb.extra_allow_syscalls.is_empty() {
        builder = builder.extra_allow_syscalls(pb.extra_allow_syscalls.clone());
    }
    if !pb.extra_deny_syscalls.is_empty() {
        builder = builder.extra_deny_syscalls(pb.extra_deny_syscalls.clone());
    }
    for rule in &pb.http_allow {
        builder = builder.http_allow(rule);
    }
    for rule in &pb.http_deny {
        builder = builder.http_deny(rule);
    }
    for c in &pb.credentials {
        builder = builder.credential_spec(c);
    }
    for rule in &pb.http_auth {
        builder = builder.http_auth(rule);
    }
    for port in &pb.http_ports {
        builder = builder.http_port(*port);
    }
    if let Some(ref ca) = pb.http_ca {
        builder = builder.http_ca(ca);
    }
    if let Some(ref key) = pb.http_key {
        builder = builder.http_key(key);
    }
    for p in &pb.http_inject_ca {
        builder = builder.http_inject_ca(p);
    }
    if let Some(ref out) = pb.http_ca_out {
        builder = builder.http_ca_out(out);
    }
    if pb.port_remap {
        builder = builder.port_remap(true);
    }
    if pb.no_randomize_memory {
        builder = builder.no_randomize_memory(true);
    }
    if pb.no_huge_pages {
        builder = builder.no_huge_pages(true);
    }
    if pb.deterministic_dirs {
        builder = builder.deterministic_dirs(true);
    }
    if pb.no_coredump {
        builder = builder.no_coredump(true);
    }

    // CLI overrides — non-clap-friendly fields (still parsed here)
    if let Some(ref m) = args.max_memory {
        builder = builder.max_memory(ByteSize::parse(m)?);
    }
    if let Some(ref ts) = args.time_start {
        builder = builder.time_start(parse_timestamp("--time-start", ts)?);
    }
    if let Some(ref s) = args.max_disk {
        builder = builder.max_disk(ByteSize::parse(s)?);
    }
    if let Some(ref s) = args.on_exit {
        builder = builder.on_exit(parse_branch_action("--on-exit", s)?);
    }
    if let Some(ref s) = args.on_error {
        builder = builder.on_error(parse_branch_action("--on-error", s)?);
    }
    for spec in &args.fs_mount {
        let (virt, host, read_only) = profile::parse_mount_spec(spec)?;
        builder = if read_only {
            builder.fs_mount_ro(virt, host)
        } else {
            builder.fs_mount(virt, host)
        };
    }
    if !args.cpu_cores.is_empty() {
        builder = builder.cpu_cores(args.cpu_cores.clone());
    }
    for spec in &args.uname {
        builder = builder.uname_spec(spec);
    }
    match &args.gpu {
        // `all` maps to an empty device list, which the core expands to every
        // present GPU; explicit indices pass through unchanged.
        Some(GpuSelection::All) => builder = builder.gpu_devices(Vec::new()),
        Some(GpuSelection::Devices(devs)) => builder = builder.gpu_devices(devs.clone()),
        None => {}
    }
    for spec in &args.env_vars {
        if let Some((k, v)) = spec.split_once('=') {
            builder = builder.env_var(k, v);
        } else {
            return Err(anyhow!("--env requires KEY=VALUE, got: {}", spec));
        }
    }

    // Auto-generated names are handled by sandlock-core's sandbox_resolve_name
    // (format: sandbox-<pid>-<counter>). Let core handle it when name is None.
    let sandbox_name = args.name.clone();

    let image_cmd: Option<Vec<String>>;
    if let Some(ref img) = args.image {
        #[cfg(not(feature = "image"))]
        return Err(anyhow!(
            "image support is disabled; enable the image feature"
        ));
        #[cfg(feature = "image")]
        {
            let image = sandlock_core::image::pull(img, None).await?;
            builder = builder.image(&image);
            image_cmd = args.cmd.is_empty().then(|| image.config.default_cmd());
        }
    } else {
        image_cmd = None;
    }

    // Derive the effective command: profile's [program] section supplies a
    // default; a trailing positional command on the CLI overrides it.
    let profile_cmd: Option<Vec<String>> =
        if args.cmd.is_empty() && args.exec_shell.is_none() && image_cmd.is_none() {
            if let Some(spec) = profile_program_spec {
                if let Some(exec) = spec.exec {
                    let exec_str = exec
                        .into_os_string()
                        .into_string()
                        .map_err(|_| anyhow!("non-UTF-8 exec path in profile"))?;
                    let mut v = vec![exec_str];
                    v.extend(spec.args);
                    Some(v)
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            None
        };

    if args.exec_shell.is_none()
        && args.cmd.is_empty()
        && image_cmd.is_none()
        && profile_cmd.is_none()
    {
        return Err(anyhow!(
            "no command specified (no trailing command and no [program].exec in profile)"
        ));
    }

    if args.no_supervisor {
        builder = builder.no_supervisor(true);
    }

    // CLI overrides — protection policy
    for s in &args.allow_degraded {
        builder = builder.allow_degraded(parse_protection(s).map_err(|e| anyhow!(e))?);
    }
    for s in &args.disable {
        builder = builder.disable(parse_protection(s).map_err(|e| anyhow!(e))?);
    }

    let policy = builder.build()?;
    let cmd_strs: Vec<&str> = if let Some(ref shell_cmd) = args.exec_shell {
        vec!["/bin/sh", "-c", shell_cmd.as_str()]
    } else if let Some(ref ic) = image_cmd {
        ic.iter().map(|s| s.as_str()).collect()
    } else if !args.cmd.is_empty() {
        args.cmd.iter().map(|s| s.as_str()).collect()
    } else if let Some(ref pc) = profile_cmd {
        pc.iter().map(|s| s.as_str()).collect()
    } else {
        // Unreachable: the check above would have returned an error.
        unreachable!("no command source available")
    };

    // Bake the instance name into the sandbox so all lifecycle methods use it.
    // When name is None, core auto-generates sandbox-<pid>-<counter>.
    let mut policy = if let Some(ref name) = sandbox_name {
        policy.with_name(name.clone())
    } else {
        policy
    };

    if args.dry_run {
        if policy.workdir.is_none() {
            return Err(anyhow!("--dry-run requires --workdir"));
        }
        policy.on_exit = BranchAction::Abort;
        policy.on_error = BranchAction::Abort;
    }

    let run = async {
        if args.wait_jobs {
            policy.create_interactive(&cmd_strs).await?;
            policy.start()?;
            policy.join().await?;
            policy.shutdown().await
        } else {
            policy.run_interactive(&cmd_strs).await
        }
    };
    let result = if let Some(secs) = args.timeout {
        match tokio::time::timeout(std::time::Duration::from_secs(secs), run).await {
            Ok(r) => r?,
            Err(_) => {
                eprintln!("sandlock: timeout after {}s", secs);
                return Ok(124);
            }
        }
    } else {
        run.await?
    };

    if args.dry_run {
        if result.changes.is_empty() {
            eprintln!("sandlock: dry-run: no filesystem changes");
        } else {
            eprintln!("sandlock: dry-run: filesystem changes:");
            for change in &result.changes {
                eprintln!("{change}");
            }
        }
    }

    if let Some(fd) = args.status_fd {
        use sandlock_core::ExitStatus as SandlockExitStatus;
        use std::io::Write as _;
        use std::os::unix::io::FromRawFd;
        let (code, signal) = match &result.exit_status {
            SandlockExitStatus::Code(c) => (*c, None),
            SandlockExitStatus::Signal(s) => (-1, Some(*s)),
            SandlockExitStatus::Killed => (-1, None),
            SandlockExitStatus::Timeout => (-1, None),
        };
        let status = SandboxStatus {
            exit_code: code,
            signal,
        };
        if let Ok(json) = serde_json::to_string(&status) {
            let mut file = unsafe { std::fs::File::from_raw_fd(fd) };
            let _ = writeln!(file, "{}", json);
            std::mem::forget(file); // Don't close the fd
        }
    }

    let exit_code = result.code().unwrap_or(1);

    // When running from a profile file and the process exits non-zero, suggest
    // extending the profile with --merge in case the failure was a denial.
    if exit_code != 0 {
        if let Some(ref path) = args.profile_file {
            if let Some(ref cmd_str) = profile_hint_cmd {
                eprintln!(
                    "hint: if a denial caused this, extend the profile with:\n  \
                     sandlock learn --merge {} -- {cmd_str}",
                    path.display()
                );
            }
        }
    }

    Ok(exit_code)
}

/// Validate that no flags incompatible with --no-supervisor are set.
fn validate_no_supervisor(args: &RunArgs) -> Result<()> {
    let pb = &args.sandbox_builder;
    let mut bad = Vec::new();

    if args.max_memory.is_some() {
        bad.push("--max-memory");
    }
    if pb.max_processes.is_some() {
        bad.push("--max-processes");
    }
    if pb.max_cpu.is_some() {
        bad.push("--max-cpu");
    }
    if pb.max_open_files.is_some() {
        bad.push("--max-open-files");
    }
    if args.timeout.is_some() {
        bad.push("--timeout");
    }
    if !pb.net_allow.is_empty() {
        bad.push("--net-allow");
    }
    if !pb.net_deny.is_empty() {
        bad.push("--net-deny");
    }
    if !pb.net_allow_bind.is_empty() {
        bad.push("--net-allow-bind");
    }
    if !pb.net_deny_bind.is_empty() {
        bad.push("--net-deny-bind");
    }
    if !pb.http_allow.is_empty() {
        bad.push("--http-allow");
    }
    if !pb.http_deny.is_empty() {
        bad.push("--http-deny");
    }
    if !pb.http_ports.is_empty() {
        bad.push("--http-port");
    }
    if pb.num_cpus.is_some() {
        bad.push("--num-cpus");
    }
    if pb.random_seed.is_some() {
        bad.push("--random-seed");
    }
    if args.time_start.is_some() {
        bad.push("--time-start");
    }
    if pb.no_randomize_memory {
        bad.push("--no-randomize-memory");
    }
    if pb.no_huge_pages {
        bad.push("--no-huge-pages");
    }
    if pb.deterministic_dirs {
        bad.push("--deterministic-dirs");
    }
    if pb.chroot.is_some() {
        bad.push("--chroot");
    }
    if args.image.is_some() {
        bad.push("--image");
    }
    if pb.user.is_some() {
        bad.push("--user");
    }
    if pb.workdir.is_some() {
        bad.push("--workdir");
    }
    if pb.cwd.is_some() {
        bad.push("--cwd");
    }
    if pb.fs_storage.is_some() {
        bad.push("--fs-storage");
    }
    if args.max_disk.is_some() {
        bad.push("--max-disk");
    }
    if pb.port_remap {
        bad.push("--port-remap");
    }
    if !args.cpu_cores.is_empty() {
        bad.push("--cpu-cores");
    }
    if !args.uname.is_empty() {
        bad.push("--uname");
    }
    if args.gpu.is_some() {
        bad.push("--gpu");
    }
    if args.dry_run {
        bad.push("--dry-run");
    }
    if args.status_fd.is_some() {
        bad.push("--status-fd");
    }
    if !pb.fs_denied.is_empty() {
        bad.push("--fs-deny");
    }
    if !args.fs_mount.is_empty() {
        bad.push("--fs-mount");
    }

    if !bad.is_empty() {
        return Err(anyhow!(
            "--no-supervisor is incompatible with: {}",
            bad.join(", ")
        ));
    }

    Ok(())
}

fn profile_source(args: &RunArgs) -> String {
    args.profile
        .as_deref()
        .map(|n| format!("profile {n}"))
        .unwrap_or_else(|| {
            let path = args
                .profile_file
                .as_ref()
                .expect("profile_source called without a loaded profile");
            format!("profile file {}", path.display())
        })
}

/// Validate profile fields against the smaller no-supervisor execution model.
///
/// No-supervisor mode only applies Landlock filesystem allow rules, the
/// deny-only seccomp blocklist, and environment changes before exec. Reject
/// profile fields that require the supervisor or other setup paths so profile
/// users do not get a silently weakened sandbox.
fn validate_no_supervisor_profile(profile: &Sandbox, source: &str) -> Result<()> {
    let mut bad = Vec::new();

    if !profile.fs_denied.is_empty() {
        bad.push("[filesystem].deny");
    }
    if !profile.net_allow.is_empty() {
        bad.push("[network].allow");
    }
    if !profile.net_deny.is_empty() {
        bad.push("[network].deny");
    }
    if !profile.net_allow_bind.is_default() {
        bad.push("[network].allow_bind");
    }
    if !profile.net_deny_bind.is_empty() {
        bad.push("[network].deny_bind");
    }
    if profile.port_remap {
        bad.push("[network].port_remap");
    }
    if !profile.http_allow.is_empty() {
        bad.push("[http].allow");
    }
    if !profile.http_deny.is_empty() {
        bad.push("[http].deny");
    }
    if !profile.http_ports.is_empty() {
        bad.push("[http].ports");
    }
    if profile.http_ca.is_some() {
        bad.push("[config].http_ca");
    }
    if profile.http_key.is_some() {
        bad.push("[config].http_key");
    }
    if profile.max_memory.is_some() {
        bad.push("[limits].memory");
    }
    if profile.max_processes.is_some() {
        bad.push("[limits].processes");
    }
    if profile.max_open_files.is_some() {
        bad.push("[limits].open_files");
    }
    if profile.max_cpu.is_some() {
        bad.push("[limits].cpu");
    }
    if profile.max_disk.is_some() {
        bad.push("[limits].disk");
    }
    if profile.gpu_devices.is_some() {
        bad.push("[limits].gpu_devices");
    }
    if profile.cpu_cores.is_some() {
        bad.push("[limits].cpu_cores");
    }
    if profile.num_cpus.is_some() {
        bad.push("[limits].num_cpus");
    }
    if !profile.uname.is_empty() {
        bad.push("[uname]");
    }
    if profile.random_seed.is_some() {
        bad.push("[determinism].random_seed");
    }
    if profile.time_start.is_some() {
        bad.push("[determinism].time_start");
    }
    if profile.deterministic_dirs {
        bad.push("[determinism].deterministic_dirs");
    }
    if profile.no_randomize_memory {
        bad.push("[determinism].no_randomize_memory");
    }
    if profile.no_huge_pages {
        bad.push("[program].no_huge_pages");
    }
    if profile.no_coredump {
        bad.push("[program].no_coredump");
    }
    if profile.workdir.is_some() {
        bad.push("[config].workdir");
    }
    if profile.fs_storage.is_some() {
        bad.push("[config].fs_storage");
    }
    if profile.cwd.is_some() {
        bad.push("[program].cwd");
    }
    if profile.user.is_some() {
        bad.push("[program].uid");
    }
    if profile.chroot.is_some() {
        bad.push("[filesystem].chroot");
    }
    if !profile.fs_mount.is_empty() {
        bad.push("[filesystem].mount");
    }
    if profile.on_exit != BranchAction::Commit {
        bad.push("[filesystem].on_exit");
    }
    if profile.on_error != BranchAction::Abort {
        bad.push("[filesystem].on_error");
    }

    if !bad.is_empty() {
        return Err(anyhow!(
            "--no-supervisor is incompatible with {} field(s): {}",
            source,
            bad.join(", ")
        ));
    }

    Ok(())
}

/// Render a parsed `NetRule` back into a `--net-allow` / `--net-deny` spec
/// string, so a profile loaded via `--profile-file` round-trips through the
/// builder. Allow and deny share one grammar. The scheme is always
/// rendered: a scheme-less spec parses as a TCP + UDP pair, so a
/// single-protocol rule must carry its scheme to round-trip exactly.
/// IPv6 is bracketed only when a port follows, and the all-ports case
/// drops the redundant `:*`.
fn parse_branch_action(flag: &str, s: &str) -> Result<BranchAction> {
    match s {
        "commit" => Ok(BranchAction::Commit),
        "abort" => Ok(BranchAction::Abort),
        "keep" => Ok(BranchAction::Keep),
        other => Err(anyhow!(
            "invalid {} value '{}': expected commit | abort | keep",
            flag,
            other
        )),
    }
}

// ============================================================
// /proc helpers for sandlock ps
// ============================================================

/// Validate a sandbox name coming from CLI argv (kill/inspect paths).
/// Mirrors `sandbox_validate_name` but returns a plain `Result` so the
/// CLI can format its own error messages.
fn validate_cli_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("sandbox name must not be empty".into());
    }
    if name.len() > 64 {
        return Err("sandbox name must be at most 64 bytes".into());
    }
    if name.contains('\0') {
        return Err("sandbox name must not contain NUL bytes".into());
    }
    if name.bytes().any(|b| b <= 0x20 || b == 0x7f) {
        return Err("sandbox name must not contain whitespace or control characters".into());
    }
    if name.contains('/') {
        return Err("sandbox name must not contain '/'".into());
    }
    if name == "." || name == ".." {
        return Err("sandbox name must not be '.' or '..'".into());
    }
    Ok(())
}

/// Query the control socket for the virtual→real port map, returning a
/// compact display string or `"-"` when the socket is missing (e.g.
/// `--no-supervisor`).
fn main_exited_row(
    name: &str,
    info: sandlock_core::control::SandboxInfo,
) -> (String, String, String, String, String) {
    let cmd = match info.live_groups {
        0 => "(main exited, idle)".to_string(),
        1 => "(main exited, 1 group)".to_string(),
        n => format!("(main exited, {n} groups)"),
    };
    (
        info.mode.unwrap_or_else(|| "running".to_string()),
        query_ports(name),
        "-".to_string(),
        "-".to_string(),
        cmd,
    )
}

fn pidfd_open(pid: i32) -> Option<std::os::fd::OwnedFd> {
    use std::os::fd::FromRawFd;
    let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
    (fd >= 0).then(|| unsafe { std::os::fd::OwnedFd::from_raw_fd(fd as i32) })
}

fn pidfd_exited(fd: &std::os::fd::OwnedFd) -> bool {
    use std::os::fd::AsRawFd;
    let mut poll = libc::pollfd {
        fd: fd.as_raw_fd(),
        events: libc::POLLIN,
        revents: 0,
    };
    unsafe { libc::poll(&mut poll, 1, 0) != 0 }
}

fn query_ports(name: &str) -> String {
    use sandlock_core::control::send_control_request;
    match send_control_request(name, "ports", serde_json::Value::Object(Default::default())) {
        Ok(resp) if resp.ok => {
            if let Some(data) = resp.data {
                let map: std::collections::HashMap<u16, u16> = match serde_json::from_value(data) {
                    Ok(m) => m,
                    Err(_) => return "-".to_string(),
                };
                if map.is_empty() {
                    return "-".to_string();
                }
                let mut entries: Vec<String> =
                    map.iter().map(|(v, r)| format!("{}→{}", v, r)).collect();
                entries.sort();
                entries.join(", ")
            } else {
                "-".to_string()
            }
        }
        _ => "-".to_string(),
    }
}

/// Read /proc/<pid>/stat and return a human-readable uptime string.
fn proc_uptime(pid: i32) -> Option<String> {
    let stat = std::fs::read_to_string(format!("/proc/{}/stat", pid)).ok()?;
    // Field 22 (0-indexed) is starttime in clock ticks since boot.
    let starttime: u64 = stat
        .split(')')
        .nth(1)?
        .split_whitespace()
        .nth(19)?
        .parse()
        .ok()?;
    let ticks_per_sec = unsafe { libc::sysconf(libc::_SC_CLK_TCK) } as u64;
    let uptime_secs = if ticks_per_sec > 0 {
        let boot_secs = proc_uptime_sys()?;
        boot_secs.saturating_sub(starttime / ticks_per_sec)
    } else {
        return None;
    };
    if uptime_secs < 60 {
        Some(format!("{}s", uptime_secs))
    } else if uptime_secs < 3600 {
        Some(format!("{}m", uptime_secs / 60))
    } else if uptime_secs < 86400 {
        Some(format!(
            "{}h{}m",
            uptime_secs / 3600,
            (uptime_secs % 3600) / 60
        ))
    } else {
        Some(format!(
            "{}d{}h",
            uptime_secs / 86400,
            (uptime_secs % 86400) / 3600
        ))
    }
}

/// Read /proc/uptime (system uptime in seconds).
fn proc_uptime_sys() -> Option<u64> {
    let s = std::fs::read_to_string("/proc/uptime").ok()?;
    let secs: f64 = s.split_whitespace().next()?.parse().ok()?;
    Some(secs as u64)
}

/// Read /proc/<pid>/cmdline and return a human-readable command string.
fn proc_cmdline(pid: i32) -> Option<String> {
    let raw = std::fs::read(format!("/proc/{}/cmdline", pid)).ok()?;
    if raw.is_empty() {
        return Some("?".to_string());
    }
    let args: Vec<&str> = raw
        .split(|b| *b == 0)
        .filter_map(|chunk| std::str::from_utf8(chunk).ok())
        .filter(|s| !s.is_empty())
        .collect();
    if args.is_empty() {
        Some("?".to_string())
    } else {
        // Truncate to ~60 chars for display.  Slice on a character
        // boundary — &joined[..57] would panic if byte 57 falls in the
        // middle of a multi-byte UTF-8 codepoint.
        let joined = args.join(" ");
        if joined.len() > 60 {
            let end = joined.floor_char_boundary(57);
            Some(format!("{}…", &joined[..end]))
        } else {
            Some(joined)
        }
    }
}

#[cfg(test)]
mod render_tests {
    use sandlock_core::sandbox::NetRule;

    #[test]
    fn render_allow_drops_redundant_all_ports_star() {
        let r = &NetRule::parse_allow("udp://*:*").unwrap()[0];
        assert_eq!(sandlock_core::format_net_rule(r), "udp://*");
    }

    #[test]
    fn render_allow_any_ip_all_ports_schemeless_pair() {
        // `:*` expands to a TCP + UDP pair; each rule renders its scheme
        // so the pair round-trips without widening.
        let rules = NetRule::parse_allow(":*").unwrap();
        let rendered: Vec<String> = rules.iter().map(sandlock_core::format_net_rule).collect();
        assert_eq!(rendered, vec!["tcp://*", "udp://*"]);
    }

    #[test]
    fn render_allow_host_ports() {
        let rules = NetRule::parse_allow("example.com:443").unwrap();
        assert_eq!(
            sandlock_core::format_net_rule(&rules[0]),
            "tcp://example.com:443"
        );
        assert_eq!(
            sandlock_core::format_net_rule(&rules[1]),
            "udp://example.com:443"
        );
    }

    #[test]
    fn render_cidr_and_ipv6_round_trip() {
        // CIDR and IPv6-literal targets render identically for allow/deny.
        assert_eq!(
            sandlock_core::format_net_rule(&NetRule::parse_allow("10.0.0.0/8:80").unwrap()[0]),
            "tcp://10.0.0.0/8:80"
        );
        assert_eq!(
            sandlock_core::format_net_rule(&NetRule::parse_deny("10.0.0.0/8").unwrap()[0]),
            "tcp://10.0.0.0/8"
        );
        assert_eq!(
            sandlock_core::format_net_rule(&NetRule::parse_allow("[::1]:443").unwrap()[0]),
            "tcp://[::1]:443"
        );
        assert_eq!(
            sandlock_core::format_net_rule(&NetRule::parse_allow("::1").unwrap()[0]),
            "tcp://::1"
        );
    }

    #[test]
    fn render_roundtrips_through_parse() {
        for spec in [
            "example.com:443",
            "udp://1.1.1.1:53",
            "icmp://github.com",
            "*",
            "udp://*",
            "tcp://*",
            "10.0.0.0/8:80",
            "[fc00::/7]:443",
            "::1",
            "1.2.3.4",
        ] {
            for r in &NetRule::parse_allow(spec).unwrap() {
                let rendered = sandlock_core::format_net_rule(r);
                // A rendered rule always carries its scheme, so it must
                // reparse to exactly one rule equal to the original.
                let reparsed = NetRule::parse_allow(&rendered).unwrap();
                assert_eq!(
                    reparsed.len(),
                    1,
                    "rendered `{rendered}` from {spec} not single"
                );
                assert_eq!(
                    *r, reparsed[0],
                    "round-trip mismatch for {spec} via `{rendered}`"
                );
            }
        }
    }
}