byleave 0.16.0

The command line of By Your Leave: runs the kernel and talks to it.
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
//! The `byleave` command line: the kernel, and the first client of its human
//! channel (D-32).
//!
//! ```text
//! byleave sandbox install | remove | remove-old
//!     The agent network block (as administrator, once); remove-old removes
//!     the one Prospero installed, once no Prospero kernel runs (D-72).
//! byleave sandbox check --data DIR          Self-test, showing each route
//! byleave run --data DIR --config FILE [--goal TEXT] [--pack NAME]
//!              [--project NAME] [--simulate] [--until-idle]
//!     Start the kernel and serve its channel. With --goal, submit it and stop
//!     when it is produced or failed; --pack names the pack it is for (needed
//!     when the configuration runs several), --project the project (D-40),
//!     --simulate runs it against simulators (FR-ACT-9). With --until-idle,
//!     stop when there is nothing left to do (an escalation waiting counts
//!     as nothing to do).
//!
//! The following talk to a running kernel. --pack may be left out while
//! one pack is loaded.
//! byleave submit --data DIR [--pack NAME] [--project NAME] [--simulate]
//!                [--under ROOT] TEXT
//!     With --under, file the goal under an open root (D-80).
//! byleave open --data DIR [--spend-micros N] [--model-calls N] [--actions N] TEXT
//!     Open a root goal that stays open (D-80), with its own budgets over its
//!     whole life; left out, the installation's defaults.
//! byleave close --data DIR ROOT [--reason TEXT]
//! byleave reopen --data DIR ROOT [--spend-micros N] [--model-calls N] [--actions N]
//!     Reopen a closed root, setting its budgets again; one left out keeps
//!     its value.
//! byleave undo --data DIR ACTION
//!     Undo an executed action, within its tool's undo window (FR-ACT-8).
//! byleave status --data DIR
//! byleave escalations --data DIR [--raw]
//! byleave answer --data DIR ID ANSWER [--note TEXT]
//!     ANSWER is `approve` or `reject` for an action, any text for a question.
//! byleave policy --data DIR [set KEY VALUE] [--pack NAME | --global | --goal ROOT]
//!     --goal sets one of an open root's own budgets (D-80).
//! byleave pack --data DIR [load NAME | remove NAME]
//!     List the loaded packs; load a pack from the pack folders, or replace
//!     the loaded one, while the others keep running; or remove one with no
//!     open goals (FR-PACK-2).
//! byleave cancel --data DIR GOAL --reason TEXT
//!     Withdraw a goal and the goals beneath it.
//! byleave kill --data DIR --reason TEXT
//! byleave release --data DIR --reason TEXT
//! byleave events --data DIR --goal ID
//! byleave watch --data DIR [--after SEQ]
//!
//! The console (M8):
//! byleave log --data DIR [--type TYPE] [--goal ID] [--text TEXT] [--after SEQ]
//!              [--limit N]
//!     Search the log (FR-HUM-2). `--type action.*` matches by prefix; a goal
//!     matches its own events and those of the goals beneath it.
//! byleave trace --data DIR EVENT
//!     An event, the causes that led to it and everything it caused.
//! byleave tree --data DIR GOAL
//!     A goal, its tasks and the goals beneath it.
//! byleave samples --data DIR [--all]
//! byleave review --data DIR SAMPLE ok|concern [--note TEXT]
//!     Actions a role proposed that the policy let through without asking,
//!     sampled for review (FR-POL-8); with --all, those reviewed too. The
//!     kernel's own runs of a pack's check criteria are not sampled: they
//!     are the pack's checks, not a role's actions.
//! byleave knowledge --data DIR [accept ID [--note TEXT] | reject ID --reason TEXT
//!                    | revert SKILL --reason TEXT]
//!     The learner's proposals (FR-HUM-4), and what to do with them.
//! byleave replay --data DIR INVOCATION [--model BINDING]
//! byleave replays --data DIR [--invocation ID]
//!     Replay a role invocation, on its recorded responses or another model;
//!     nothing it proposes is acted on (FR-AUD-1 to FR-AUD-3).
//! byleave verify --data DIR
//!     Check the log's hash chain (FR-LOG-6), and every device signature in
//!     it (FR-AUTH-5). With no kernel running it reads the log itself, so it
//!     works on a log the kernel refuses.
//!
//! Owner devices (chat stage B, D-64 to D-68):
//! byleave device --data DIR [enrol NAME [--recover] | revoke NAME --reason TEXT]
//!     List the devices; enrol this machine's Windows Hello key as NAME (the
//!     first device, and a recovery, from a terminal run as administrator);
//!     or revoke one. Once a device is enrolled, every command that decides
//!     something is signed: `byleave` shows what the kernel prepared, and
//!     Windows Hello asks you to confirm.
//! byleave withdraw --data DIR ACTION --reason TEXT
//!     Withdraw the approval of a class 3 action still in its delay.
//! ```

use by_your_leave::config::Config;
use by_your_leave::human;
use by_your_leave::kernel::{CrashPoint, Kernel, KernelOptions};
use by_your_leave::protocol::human::{
    AdapterView, EscalationView, HumanRequest, HumanResponse, PackView, RootBudgets, StatusView,
};
use by_your_leave::sandbox::{self, Sandbox};
use by_your_leave::state::GoalStatus;
use serde_json::Value;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let rest = args.get(1..).unwrap_or_default();
    let result = match args.first().map(String::as_str) {
        Some("sandbox") => sandbox_cmd(rest),
        Some("run") => run(rest),
        Some(
            cmd @ ("submit" | "open" | "close" | "reopen" | "undo" | "status" | "escalations"
            | "answer" | "policy" | "pack" | "kill" | "release" | "events" | "watch"
            | "result" | "cancel" | "log" | "trace" | "tree" | "samples" | "review"
            | "knowledge" | "replay" | "replays" | "device" | "withdraw"),
        ) => client(cmd, rest),
        Some("verify") => verify(rest),
        _ => Err(USAGE.into()),
    };
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("{e}");
            ExitCode::FAILURE
        }
    }
}

const USAGE: &str = "usage:
  byleave sandbox install | remove | remove-old
  byleave sandbox check --data DIR
  byleave run --data DIR --config FILE [--goal TEXT] [--pack NAME] [--project NAME]
               [--simulate] [--until-idle]
  byleave submit --data DIR [--pack NAME] [--project NAME] [--simulate] [--under ROOT] TEXT
  byleave open --data DIR [--spend-micros N] [--model-calls N] [--actions N] TEXT
      Open a root goal that stays open, for one piece of work: file later goals
      under it with submit --under. Its budgets cover all of them, for its life.
  byleave close --data DIR ROOT [--reason TEXT]
  byleave reopen --data DIR ROOT [--spend-micros N] [--model-calls N] [--actions N]
  byleave undo --data DIR ACTION
  byleave status --data DIR
  byleave escalations --data DIR [--raw]
  byleave answer --data DIR ID ANSWER [--note TEXT]
  byleave policy --data DIR [set KEY VALUE] [--pack NAME | --global | --goal ROOT]
  byleave result --data DIR GOAL
  byleave pack --data DIR [load NAME | remove NAME]
  byleave cancel --data DIR GOAL --reason TEXT
  byleave kill --data DIR --reason TEXT
  byleave release --data DIR --reason TEXT
  byleave events --data DIR --goal ID
  byleave watch --data DIR [--after SEQ]
  byleave log --data DIR [--type TYPE] [--goal ID] [--text TEXT] [--after SEQ] [--limit N]
  byleave trace --data DIR EVENT
  byleave tree --data DIR GOAL
  byleave samples --data DIR [--all]
      Actions a role proposed that ran without asking, sampled for you to
      review. The kernel's own runs of a pack's check criteria are not sampled.
  byleave review --data DIR SAMPLE ok|concern [--note TEXT]
  byleave knowledge --data DIR [accept ID [--note TEXT] | reject ID --reason TEXT
                     | revert SKILL --reason TEXT]
  byleave replay --data DIR INVOCATION [--model BINDING]
  byleave replays --data DIR [--invocation ID]
  byleave verify --data DIR
  byleave device --data DIR [enrol NAME [--recover] | revoke NAME --reason TEXT]
      The owner devices that sign. Enrol the first one, or recover, from a
      terminal run as administrator. Once one is enrolled, every command that
      decides something is signed with Windows Hello.
  byleave withdraw --data DIR ACTION --reason TEXT
      Withdraw the approval of a class 3 action still in its delay.";

/// Flags that take a value.
const VALUED: [&str; 17] = [
    "--under",
    "--spend-micros",
    "--model-calls",
    "--actions",
    "--pack",
    "--data",
    "--config",
    "--goal",
    "--note",
    "--reason",
    "--after",
    "--project",
    "--type",
    "--text",
    "--limit",
    "--model",
    "--invocation",
];

fn flag(args: &[String], name: &str) -> Option<String> {
    args.iter()
        .position(|a| a == name)
        .and_then(|i| args.get(i + 1).cloned())
}

fn has(args: &[String], name: &str) -> bool {
    args.iter().any(|a| a == name)
}

/// Arguments that are not flags or flag values.
fn positionals(args: &[String]) -> Vec<String> {
    let mut out = Vec::new();
    let mut skip = false;
    for a in args {
        if skip {
            skip = false;
        } else if VALUED.contains(&a.as_str()) {
            skip = true;
        } else if !a.starts_with("--") {
            out.push(a.clone());
        }
    }
    out
}

fn data_dir(args: &[String]) -> Result<PathBuf, String> {
    flag(args, "--data")
        .map(PathBuf::from)
        .ok_or_else(|| USAGE.into())
}

fn sandbox_cmd(args: &[String]) -> Result<(), String> {
    match args.first().map(String::as_str) {
        #[cfg(windows)]
        Some("install") => {
            for line in sandbox::wfp::install()? {
                println!("{line}");
            }
            println!(
                "Agent network block installed for profile `{}`.",
                sandbox::PROFILE
            );
            Ok(())
        }
        #[cfg(windows)]
        Some("remove") => {
            for line in sandbox::wfp::remove()? {
                println!("{line}");
            }
            println!("Agent network block removed.");
            Ok(())
        }
        #[cfg(windows)]
        Some("remove-old") => {
            for line in sandbox::wfp::remove_old()? {
                println!("{line}");
            }
            println!("The network block Prospero installed is removed (D-72).");
            Ok(())
        }
        Some("check") => {
            let data = data_dir(args)?;
            std::fs::create_dir_all(&data).map_err(|e| e.to_string())?;
            // The log must exist, or "cannot read the log" would prove nothing.
            drop(
                by_your_leave::log::EventLog::open(data.join("log.db"))
                    .map_err(|e| e.to_string())?,
            );
            let options = KernelOptions::beside_current_exe().map_err(|e| e.to_string())?;
            let sb = Sandbox::prepare(&options.agent_exe, &data.join("sandbox").join("bin"))?;
            let report = sandbox::self_test(&sb, &data.join("log.db"), &data)?;
            for c in &report.checks {
                let verdict = match (c.result.open, sandbox::KNOWN_LIMITS.contains(&c.route)) {
                    (false, _) => "closed",
                    (true, true) => "KNOWN ",
                    (true, false) => "OPEN  ",
                };
                println!("{verdict}  {:<36} {}", c.route, c.result.detail);
            }
            if !report.known_open().is_empty() {
                println!(
                    "\nKNOWN: open on every Windows machine, and not closed by By Your Leave (D-44)."
                );
            }
            let open = report.open_routes();
            if open.is_empty() {
                println!("\nEvery route is closed.");
                Ok(())
            } else {
                Err(format!(
                    "\n{} route(s) open. The kernel will refuse to start.",
                    open.len()
                ))
            }
        }
        _ => Err(USAGE.into()),
    }
}

fn run(args: &[String]) -> Result<(), String> {
    let data = data_dir(args)?;
    let config = Config::load(&PathBuf::from(flag(args, "--config").ok_or(USAGE)?))?;
    #[allow(unused_mut)]
    let mut options = KernelOptions::beside_current_exe().map_err(|e| e.to_string())?;
    // Fault injection for the crash-recovery tests. Debug builds only.
    #[cfg(debug_assertions)]
    if let Ok(spec) = std::env::var("BYLEAVE_TEST_CRASH") {
        options.crash = CrashPoint::parse(&spec);
    }
    let _ = CrashPoint::parse; // used in debug builds

    let mut kernel = Kernel::open(&data, config, options).map_err(|e| e.to_string())?;
    let goal = match flag(args, "--goal") {
        Some(text) => Some(
            kernel
                .submit_to(
                    flag(args, "--pack").as_deref(),
                    &text,
                    flag(args, "--project").as_deref(),
                    has(args, "--simulate"),
                )
                .map_err(|e| e.to_string())?,
        ),
        None => None,
    };

    if has(args, "--until-idle") {
        kernel.run_until_idle().map_err(|e| e.to_string())?;
    } else {
        if goal.is_none() {
            println!("Kernel running on {}. Stop it with Ctrl+C.", data.display());
            if !kernel.config().clients.is_empty() {
                // What a client's MCP server is given (D-56): the client's
                // account may not be able to read the data folder.
                println!(
                    "Client channel: {}",
                    human::client_pipe_name(&data).unwrap_or_default()
                );
            }
        }
        let mut shown = BTreeSet::new();
        kernel
            .serve(|k| {
                for id in k.state().pending_escalations() {
                    if shown.insert(id) {
                        println!(
                            "waiting for you: escalation {id}\n  see it with `byleave escalations --data {}`",
                            data.display()
                        );
                    }
                }
                goal.is_some_and(|g| k.goal_finished(g))
            })
            .map_err(|e| e.to_string())?;
    }
    report(&kernel, goal);
    Ok(())
}

fn report(kernel: &Kernel, only: Option<by_your_leave::log::GoalId>) {
    for (id, g) in &kernel.state().goals {
        if only.is_some_and(|x| x != *id) {
            continue;
        }
        let status = match &g.status {
            GoalStatus::Submitted => "submitted".to_owned(),
            GoalStatus::Working => "working".to_owned(),
            GoalStatus::Produced { .. } if kernel.goal_finished(*id) => "work produced".to_owned(),
            GoalStatus::Produced { .. } => "work produced, waiting for its check".to_owned(),
            GoalStatus::Completed { .. } => "completed: work produced and checked".to_owned(),
            GoalStatus::Failed { reason } => format!("failed: {reason}"),
        };
        println!("goal {id}: {status}");
        if let Ok(Some((_, Some(output)))) = kernel.goal_result(*id) {
            println!(
                "{}",
                serde_json::to_string_pretty(&output).unwrap_or_default()
            );
        }
        if let Some(u) = kernel.state().usage.get(id) {
            println!(
                "model calls: {}, tokens in/out: {}/{}, cost: ${:.6}",
                u.model_calls,
                u.input_tokens,
                u.output_tokens,
                u.cost_micros as f64 / 1e6
            );
        }
    }
}

// -- the human channel's command-line client ----------------------------------

fn send(data: &Path, request: HumanRequest) -> Result<Value, String> {
    match human::request(data, request)? {
        HumanResponse::Ok { result } => Ok(result),
        HumanResponse::Error { message } => Err(message),
        HumanResponse::Event { .. } => Err("unexpected event from the kernel".into()),
    }
}

/// Send `request`. Once a device is enrolled, a request that decides
/// something is signed (D-65): by this machine's enrolled device, with
/// Windows Hello.
fn ask(data: &Path, request: HumanRequest) -> Result<Value, String> {
    let may_decide = matches!(
        request,
        HumanRequest::Answer { .. }
            | HumanRequest::SetPolicy { .. }
            | HumanRequest::OpenRoot {
                budgets: Some(_),
                ..
            }
            | HumanRequest::ReopenRoot { .. }
            | HumanRequest::SetRootBudget { .. }
            | HumanRequest::Undo { .. }
            | HumanRequest::LoadPack { .. }
            | HumanRequest::RemovePack { .. }
            | HumanRequest::ReleaseKillSwitch { .. }
            | HumanRequest::AcceptKnowledge { .. }
            | HumanRequest::RejectKnowledge { .. }
            | HumanRequest::RevertKnowledge { .. }
            | HumanRequest::RevokeDevice { .. }
            | HumanRequest::EnrolDevice { .. }
    );
    if !may_decide {
        return send(data, request);
    }
    match local_device(data)? {
        Ok(Some(device)) => signed(data, request, &device),
        Ok(None) => send(data, request),
        // Devices are enrolled, none of them here: what needs no signature
        // still goes through.
        Err(enrolled) => send(data, request).map_err(|e| {
            if e.contains("must be signed") {
                format!(
                    "{e}. The enrolled devices are {}, and none of their keys is on this \
                     machine",
                    enrolled.join(", ")
                )
            } else {
                e
            }
        }),
    }
}

/// The enrolled device whose key this machine holds; `Ok(None)` if none is
/// enrolled; `Err` with the enrolled devices' names if none of their keys
/// is here.
#[cfg(windows)]
fn local_device(data: &Path) -> Result<Result<Option<String>, Vec<String>>, String> {
    use by_your_leave::hello;
    let devices = send(data, HumanRequest::Devices)?;
    let active: Vec<&str> = devices
        .as_array()
        .into_iter()
        .flatten()
        .filter(|d| d["revoked"].is_null())
        .filter_map(|d| d["name"].as_str())
        .collect();
    if active.is_empty() {
        return Ok(Ok(None));
    }
    for name in &active {
        if hello::exists(&hello::find_key(data, name)?) {
            return Ok(Ok(Some((*name).to_owned())));
        }
    }
    Ok(Err(active.iter().map(|n| (*n).to_owned()).collect()))
}

#[cfg(not(windows))]
fn local_device(_data: &Path) -> Result<Result<Option<String>, Vec<String>>, String> {
    Ok(Ok(None))
}

/// Prepare `request`, show what the kernel prepared, have Windows Hello
/// sign it as `device`, and send the signature (D-66).
#[cfg(windows)]
fn signed(data: &Path, request: HumanRequest, device: &str) -> Result<Value, String> {
    sign_as(data, request, device, device)
}

#[cfg(not(windows))]
fn signed(_data: &Path, _request: HumanRequest, _device: &str) -> Result<Value, String> {
    Err("signing needs Windows Hello (D-64)".into())
}

/// As `signed`, with the statement signed by the key named for `key_of`:
/// the device's own, or for a first enrolment or a recovery the new one.
#[cfg(windows)]
fn sign_as(
    data: &Path,
    request: HumanRequest,
    device: &str,
    key_of: &str,
) -> Result<Value, String> {
    use by_your_leave::hello;
    let prepared = send(
        data,
        HumanRequest::Prepare {
            request: Box::new(request.clone()),
            device: device.to_owned(),
        },
    );
    let prepared = match prepared {
        Ok(p) => p,
        // A role's question: it decides nothing.
        Err(e) if e.contains("is not an authority operation") => return send(data, request),
        Err(e) => return Err(e),
    };
    let statement = prepared["statement"].as_str().unwrap_or_default();
    let challenge = prepared["challenge"].as_str().unwrap_or_default();
    print_prepared(&prepared["view"], statement);
    println!("Windows Hello will ask you to confirm, as device `{device}`.");
    let signature = hello::sign(&hello::find_key(data, key_of)?, statement.as_bytes())?;
    send(
        data,
        HumanRequest::Signed {
            challenge: challenge.to_owned(),
            signature,
        },
    )
}

/// What a device is about to sign, from the kernel's data (FR-AUTH-7), as
/// every front end shows it (D-91).
#[cfg(windows)]
fn print_prepared(view: &Value, statement: &str) {
    let parts = by_your_leave_approval::view(view, statement);
    print!("{}", by_your_leave_approval::text(&parts));
}

/// `byleave device enrol`: make this machine's Windows Hello key for the
/// device, and enrol it (D-67).
#[cfg(windows)]
fn enrol(data: &Path, name: &str, recover: bool) -> Result<Value, String> {
    use by_your_leave::hello;
    if !hello::supported()? {
        return Err(
            "Windows Hello is not set up for this account: set up a PIN in Settings, Accounts, \
             Sign-in options, then try again"
                .into(),
        );
    }
    let devices = send(data, HumanRequest::Devices)?;
    let any = devices
        .as_array()
        .into_iter()
        .flatten()
        .any(|d| d["revoked"].is_null());
    // The first device and a recovery need an elevated caller with a
    // prompt (D-67). Say so before making a key the kernel would refuse;
    // the kernel checks again.
    if recover || !any {
        match human::current_elevation()? {
            human::Elevation::Prompted => {}
            human::Elevation::No => {
                return Err(
                    "the first device, and a recovery, are enrolled only from an \
                            elevated `byleave` (D-67): run it from a terminal opened as \
                            administrator"
                        .into(),
                );
            }
            human::Elevation::Silent => {
                return Err(
                    "this terminal is elevated, but User Account Control elevates \
                            without asking, so the kernel will refuse the enrolment (D-67): set \
                            it to ask, on the secure desktop (CHAT_SETUP.md, stage B, step 2)"
                        .into(),
                );
            }
        }
    }
    let key = hello::key_name(data, name)?;
    println!("Windows Hello will ask you to confirm, to make the key for `{name}`.");
    let public_key = hello::create(&key)?;
    let request = HumanRequest::EnrolDevice {
        name: name.to_owned(),
        public_key,
        recover,
    };
    // The first device and a recovery are signed by the new key itself;
    // a later one by a device already enrolled.
    let result = if recover || !any {
        sign_as(data, request, name, name)
    } else {
        match local_device(data)? {
            Ok(Some(signer)) => sign_as(data, request, &signer, &signer),
            _ => Err("no enrolled device's key is on this machine to sign for it".into()),
        }
    };
    if result.is_err() {
        let _ = hello::delete(&key);
    }
    result
}

#[cfg(not(windows))]
fn enrol(_data: &Path, _name: &str, _recover: bool) -> Result<Value, String> {
    Err("devices need Windows Hello (D-64)".into())
}

fn client(cmd: &str, args: &[String]) -> Result<(), String> {
    let data = data_dir(args)?;
    let pos = positionals(args);
    let need = |name: &str| flag(args, name).ok_or_else(|| format!("{cmd} needs {name}"));
    match cmd {
        "submit" => {
            let text = pos.join(" ");
            let request = match flag(args, "--under") {
                Some(under) => HumanRequest::FileGoal {
                    under,
                    description: text,
                    project: flag(args, "--project"),
                    simulate: has(args, "--simulate"),
                    pack: flag(args, "--pack"),
                },
                None => HumanRequest::SubmitGoal {
                    description: text,
                    project: flag(args, "--project"),
                    simulate: has(args, "--simulate"),
                    pack: flag(args, "--pack"),
                },
            };
            let r = ask(&data, request)?;
            println!("goal {}", r["goal"].as_str().unwrap_or("?"));
        }
        "open" => {
            let budgets = root_budgets(args)?;
            let r = ask(
                &data,
                HumanRequest::OpenRoot {
                    description: pos.join(" "),
                    budgets: open_roots_any(&budgets).then_some(budgets),
                },
            )?;
            let id = r["goal"].as_str().unwrap_or("?");
            println!("root {id} opened: file goals under it with `byleave submit --under {id}`");
        }
        "close" => {
            let [root] = pos.as_slice() else {
                return Err("usage: byleave close --data DIR ROOT [--reason TEXT]".into());
            };
            ask(
                &data,
                HumanRequest::CloseRoot {
                    goal: root.clone(),
                    reason: flag(args, "--reason"),
                },
            )?;
            println!("root {root} closed: it takes no new goal");
        }
        "reopen" => {
            let [root] = pos.as_slice() else {
                return Err("usage: byleave reopen --data DIR ROOT [--spend-micros N] \
                            [--model-calls N] [--actions N]"
                    .into());
            };
            let r = ask(
                &data,
                HumanRequest::ReopenRoot {
                    goal: root.clone(),
                    budgets: root_budgets(args)?,
                },
            )?;
            let b = &r["budgets"];
            println!(
                "root {root} reopened, with ${:.2} of model spend, {} model calls and {} actions \
                 over its whole life",
                b["spend_micros"].as_u64().unwrap_or(0) as f64 / 1e6,
                b["model_calls"],
                b["actions"]
            );
        }
        "result" => {
            let [goal, ..] = pos.as_slice() else {
                return Err("usage: byleave result --data DIR GOAL".into());
            };
            let r = ask(&data, HumanRequest::GoalResult { goal: goal.clone() })?;
            println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());
        }
        "undo" => {
            let [action, ..] = pos.as_slice() else {
                return Err("usage: byleave undo --data DIR ACTION".into());
            };
            let r = ask(
                &data,
                HumanRequest::Undo {
                    action: action.clone(),
                },
            )?;
            println!("undone ({})", r["undone"].as_str().unwrap_or("?"));
        }
        "status" => {
            let v: StatusView = parse(ask(&data, HumanRequest::Status)?)?;
            for g in &v.goals {
                let detail = g
                    .detail
                    .as_deref()
                    .map(|d| format!(" ({d})"))
                    .unwrap_or_default();
                println!(
                    "goal {}  {}{detail}  [{}]\n  {}",
                    g.id, g.status, g.pack, g.description
                );
                if let Some(parent) = &g.parent {
                    println!(
                        "  for goal {parent} (root {})",
                        g.root.as_deref().unwrap_or("?")
                    );
                }
                if let Some(under) = &g.under {
                    println!("  under open root {under}");
                }
            }
            println!();
            for r in &v.open_roots {
                let dollars = |m: u64| format!("${:.2}", m as f64 / 1e6);
                let by = r
                    .client
                    .as_deref()
                    .map(|c| format!(", opened by client `{c}`"))
                    .unwrap_or_default();
                println!(
                    "root {}  {}{by}: {}\n  {} goal(s) under it; {} spent of {}, {} of {} \
                     model calls, {} of {} actions, over its whole life",
                    r.id,
                    if r.open { "open" } else { "closed" },
                    r.description,
                    r.goals.len(),
                    dollars(r.used_spend_micros),
                    dollars(r.budget_spend_micros),
                    r.used_model_calls,
                    r.budget_model_calls,
                    r.used_actions,
                    r.budget_actions
                );
            }
            for d in &v.days {
                let whose = if d.scope == "kernel" {
                    "every pack together".to_owned()
                } else if let Some(c) = d.scope.strip_prefix("client:") {
                    format!("client `{c}`")
                } else {
                    format!("pack `{}`", d.scope)
                };
                let dollars = |m: u64| format!("${:.2}", m as f64 / 1e6);
                let of = |limit: Option<u64>, show: &dyn Fn(u64) -> String| {
                    limit.map_or_else(|| "no limit".to_owned(), |l| format!("of {}", show(l)))
                };
                println!(
                    "today (UTC), {whose}: {} spent ({}), {} ({}), {} ({})",
                    dollars(d.used_spend_micros),
                    of(d.spend_micros, &dollars),
                    count(d.used_model_calls, "model call", "model calls"),
                    of(d.model_calls, &|n| n.to_string()),
                    count(d.used_actions, "action", "actions"),
                    of(d.actions, &|n| n.to_string()),
                );
            }
            for p in &v.packs {
                println!(
                    "pack `{}`: actions of class {} and above wait for you",
                    p.pack, p.threshold
                );
            }
            match &v.kill_switch {
                Some(reason) => println!("kill switch ENGAGED: {reason}"),
                None => println!("kill switch released"),
            }
            if let Some(t) = &v.tool_sandbox {
                match (&t.engine, &t.reason) {
                    (Some(engine), _) => println!("tool sandbox {} on engine {engine}", t.state),
                    (None, Some(reason)) => println!("tool sandbox {}: {reason}", t.state),
                    (None, None) => println!("tool sandbox {}", t.state),
                }
            }
            for a in &v.adapters {
                println!("{}", adapter_line(a));
            }
            println!("{} escalation(s) waiting", v.escalations.len());
        }
        "escalations" => {
            let views: Vec<EscalationView> = parse(ask(&data, HumanRequest::Escalations)?)?;
            if views.is_empty() {
                println!("Nothing is waiting for you.");
            }
            for v in &views {
                print_escalation(v, has(args, "--raw"));
            }
        }
        "answer" => {
            let [id, answer, ..] = pos.as_slice() else {
                return Err("usage: byleave answer --data DIR ID ANSWER [--note TEXT]".into());
            };
            ask(
                &data,
                HumanRequest::Answer {
                    escalation: id.clone(),
                    answer: answer.clone(),
                    note: flag(args, "--note"),
                },
            )?;
            println!("answered");
        }
        "policy" => match pos.as_slice() {
            [] => {
                let packs: Vec<PackView> = parse(ask(&data, HumanRequest::Packs)?)?;
                for p in packs
                    .iter()
                    .filter(|p| flag(args, "--pack").is_none_or(|name| name == p.name))
                {
                    let v = &p.policy;
                    println!(
                        "pack `{}`: threshold {} (actions of that class and above wait for you)",
                        v.pack, v.threshold
                    );
                    println!(
                        "  budgets per root goal: ${:.2} of model spend (budget.spend_micros = \
                         {}), {} model calls (budget.model_calls), {} actions (budget.actions)",
                        v.budget_spend_micros as f64 / 1e6,
                        v.budget_spend_micros,
                        v.budget_model_calls,
                        v.budget_actions
                    );
                    println!(
                        "  class 3 approvals wait {} s before the action runs \
                         (class3.delay_seconds), once a device signs them",
                        v.class3_delay_seconds
                    );
                }
            }
            [set, key, value] if set == "set" => {
                let value: Value =
                    serde_json::from_str(value).unwrap_or_else(|_| Value::String(value.clone()));
                let request = match flag(args, "--goal") {
                    Some(goal) => HumanRequest::SetRootBudget {
                        goal,
                        key: key.clone(),
                        value,
                    },
                    None => HumanRequest::SetPolicy {
                        key: key.clone(),
                        value,
                        pack: flag(args, "--pack"),
                        global: has(args, "--global"),
                    },
                };
                let r = ask(&data, request)?;
                if r["changed"] == true {
                    println!("policy changed and logged");
                } else {
                    println!("already set to that value");
                }
            }
            _ => {
                return Err(
                    "usage: byleave policy --data DIR [set KEY VALUE] [--pack NAME | --global \
                     | --goal ROOT]"
                        .into(),
                );
            }
        },
        "pack" => match pos.as_slice() {
            [] => {
                let packs: Vec<PackView> = parse(ask(&data, HumanRequest::Packs)?)?;
                for p in &packs {
                    println!(
                        "pack `{}` {}  ({} open goal(s))",
                        p.name, p.version, p.open_goals
                    );
                    if let Some(d) = &p.description {
                        println!("  {d}");
                    }
                }
            }
            [op, name] if op == "load" => {
                let r = ask(&data, HumanRequest::LoadPack { name: name.clone() })?;
                if r["changed"] == true {
                    println!(
                        "pack `{name}` {} loaded and logged",
                        r["version"].as_str().unwrap_or("?")
                    );
                } else {
                    println!("pack `{name}` is already loaded at that version");
                }
                if let Some(state) = r["tool_sandbox"]["state"].as_str() {
                    match r["tool_sandbox"]["reason"].as_str() {
                        Some(reason) => println!("tool sandbox {state}: {reason}"),
                        None => println!("tool sandbox {state}"),
                    }
                }
            }
            [op, name] if op == "remove" => {
                ask(&data, HumanRequest::RemovePack { name: name.clone() })?;
                println!("pack `{name}` removed");
            }
            _ => return Err("usage: byleave pack --data DIR [load NAME | remove NAME]".into()),
        },
        "cancel" => {
            let [goal] = pos.as_slice() else {
                return Err("usage: byleave cancel --data DIR GOAL --reason TEXT".into());
            };
            let r = ask(
                &data,
                HumanRequest::CancelGoal {
                    goal: goal.clone(),
                    reason: need("--reason")?,
                },
            )?;
            for g in r["cancelled"].as_array().into_iter().flatten() {
                println!("goal {} cancelled", g.as_str().unwrap_or_default());
            }
        }
        "kill" => {
            ask(
                &data,
                HumanRequest::EngageKillSwitch {
                    reason: need("--reason")?,
                },
            )?;
            println!("kill switch engaged: no action will execute until it is released");
        }
        "release" => {
            ask(
                &data,
                HumanRequest::ReleaseKillSwitch {
                    reason: need("--reason")?,
                },
            )?;
            println!("kill switch released");
        }
        "events" => {
            let events = ask(
                &data,
                HumanRequest::GoalEvents {
                    goal: need("--goal")?,
                },
            )?;
            for e in events.as_array().into_iter().flatten() {
                println!("{}", event_line(e));
            }
        }
        "watch" => {
            let after = flag(args, "--after")
                .and_then(|a| a.parse().ok())
                .unwrap_or(0);
            human::subscribe(&data, after, |e| {
                println!("{}", event_line(&e));
                true
            })?;
        }
        "log" => {
            let number = |name: &str| -> Result<Option<u64>, String> {
                flag(args, name)
                    .map(|v| v.parse().map_err(|_| format!("{name} takes a number")))
                    .transpose()
            };
            let r = ask(
                &data,
                HumanRequest::SearchLog {
                    event_type: flag(args, "--type"),
                    goal: flag(args, "--goal"),
                    text: flag(args, "--text"),
                    after_seq: number("--after")?,
                    limit: number("--limit")?,
                },
            )?;
            let events = r["events"].as_array().cloned().unwrap_or_default();
            for e in &events {
                println!(
                    "{}  {}",
                    event_line(e),
                    e["id"].as_str().unwrap_or_default()
                );
            }
            if r["more"] == true
                && let Some(last) = events.last()
            {
                println!("... more: --after {}", last["seq"]);
            }
        }
        "trace" => {
            let [event] = pos.as_slice() else {
                return Err("usage: byleave trace --data DIR EVENT".into());
            };
            let r = ask(
                &data,
                HumanRequest::Trace {
                    event: event.clone(),
                },
            )?;
            println!("caused by:");
            for e in r["causes"].as_array().into_iter().flatten() {
                println!("  {}", event_line(e));
            }
            println!("the event:\n> {}", event_line(&r["event"]));
            println!("what it caused:");
            print_effects(&r["effects"], 1);
            if r["complete"] == false {
                println!("  ... (cut short: follow a later event with `byleave trace`)");
            }
        }
        "tree" => {
            let [goal] = pos.as_slice() else {
                return Err("usage: byleave tree --data DIR GOAL".into());
            };
            let r = ask(&data, HumanRequest::GoalTree { goal: goal.clone() })?;
            print_tree(&r, 0);
        }
        "samples" => {
            let r = ask(
                &data,
                HumanRequest::Samples {
                    all: has(args, "--all"),
                },
            )?;
            let samples = r.as_array().cloned().unwrap_or_default();
            if samples.is_empty() {
                println!("no sampled action waits for review");
            }
            for s in &samples {
                let review = match s["reviewed"].as_object() {
                    Some(r) => format!(
                        "reviewed: {}{}",
                        r["verdict"].as_str().unwrap_or("?"),
                        r["note"]
                            .as_str()
                            .map(|n| format!(" ({n})"))
                            .unwrap_or_default()
                    ),
                    None => "not reviewed".to_owned(),
                };
                println!(
                    "sample {}  [{review}]  {} by role `{}` (class {}), pack `{}`",
                    s["id"].as_str().unwrap_or("?"),
                    s["tool"].as_str().unwrap_or("?"),
                    s["role"].as_str().unwrap_or("?"),
                    s["class"],
                    s["pack"].as_str().unwrap_or("?"),
                );
                println!("  arguments: {}", s["arguments"]);
                println!("  result: {}", s["result"]);
                for e in s["events"].as_array().into_iter().flatten() {
                    println!("    {}", event_line(e));
                }
                println!();
            }
        }
        "review" => {
            let [sample, verdict] = pos.as_slice() else {
                return Err(
                    "usage: byleave review --data DIR SAMPLE ok|concern [--note TEXT]".into(),
                );
            };
            ask(
                &data,
                HumanRequest::ReviewSample {
                    sample: sample.clone(),
                    verdict: verdict.clone(),
                    note: flag(args, "--note"),
                },
            )?;
            println!("sample {sample} reviewed: {verdict}");
        }
        "knowledge" => match pos.as_slice() {
            [] => {
                let r = ask(&data, HumanRequest::Knowledge)?;
                let items = r.as_array().cloned().unwrap_or_default();
                if items.is_empty() {
                    println!("the learner has proposed nothing");
                }
                for p in &items {
                    println!(
                        "proposal {}  {}  skill `{}`, file `{}`{}",
                        p["id"].as_str().unwrap_or("?"),
                        p["status"].as_str().unwrap_or("?"),
                        p["skill"].as_str().unwrap_or("?"),
                        p["file"].as_str().unwrap_or("?"),
                        if p["from_observation"] == true {
                            "  (built from content from the environment)"
                        } else {
                            ""
                        },
                    );
                    println!("  why: {}", p["rationale"].as_str().unwrap_or(""));
                    if let Some(r) = p["reason"].as_str() {
                        println!("  {}: {r}", p["status"].as_str().unwrap_or(""));
                    }
                    if p["status"] == "proposed" {
                        println!("  the change, `-` the text now, `+` the text proposed:");
                        print_diff(
                            p["base_content"].as_str().unwrap_or(""),
                            p["content"].as_str().unwrap_or(""),
                        );
                    }
                    println!();
                }
            }
            [op, id] if op == "accept" => {
                let r = ask(
                    &data,
                    HumanRequest::AcceptKnowledge {
                        proposal: id.clone(),
                        note: flag(args, "--note"),
                    },
                )?;
                println!(
                    "accepted: roles are given version {} from their next load",
                    r["version"].as_str().unwrap_or("?")
                );
            }
            [op, id] if op == "reject" => {
                ask(
                    &data,
                    HumanRequest::RejectKnowledge {
                        proposal: id.clone(),
                        reason: need("--reason")?,
                    },
                )?;
                println!("rejected");
            }
            [op, skill] if op == "revert" => {
                let r = ask(
                    &data,
                    HumanRequest::RevertKnowledge {
                        skill: skill.clone(),
                        reason: need("--reason")?,
                    },
                )?;
                println!(
                    "reverted: skill `{skill}` is at version {} again",
                    r["version"].as_str().unwrap_or("?")
                );
            }
            _ => {
                return Err(
                    "usage: byleave knowledge --data DIR [accept ID | reject ID \
                     --reason TEXT | revert SKILL --reason TEXT]"
                        .into(),
                );
            }
        },
        "replay" => {
            let [invocation] = pos.as_slice() else {
                return Err("usage: byleave replay --data DIR INVOCATION [--model BINDING]".into());
            };
            let r = ask(
                &data,
                HumanRequest::Replay {
                    invocation: invocation.clone(),
                    model: flag(args, "--model"),
                },
            )?;
            print_replay(&r);
        }
        "replays" => {
            let r = ask(
                &data,
                HumanRequest::Replays {
                    invocation: flag(args, "--invocation"),
                },
            )?;
            for replay in r.as_array().into_iter().flatten() {
                print_replay(replay);
            }
        }
        "device" => match pos.as_slice() {
            [] => {
                let devices = ask(&data, HumanRequest::Devices)?;
                let list = devices.as_array().cloned().unwrap_or_default();
                if list.is_empty() {
                    println!(
                        "no device is enrolled: nothing is signed, and class 3 actions are \
                         rejected (D-58)"
                    );
                }
                for d in list {
                    let state = match d["revoked"].as_str() {
                        Some(r) => format!("revoked by {r}"),
                        None => "enrolled".to_owned(),
                    };
                    let key = d["key"].as_str().unwrap_or("?");
                    println!(
                        "{}  {state}  key {}",
                        d["name"].as_str().unwrap_or("?"),
                        &key[..key.len().min(16)]
                    );
                }
            }
            [op, name] if op == "enrol" => {
                let r = enrol(&data, name, has(args, "--recover"))?;
                println!("device `{name}` enrolled");
                for other in r["revoked"].as_array().into_iter().flatten() {
                    println!("device `{}` revoked", other.as_str().unwrap_or("?"));
                }
            }
            [op, name] if op == "revoke" => {
                ask(
                    &data,
                    HumanRequest::RevokeDevice {
                        name: name.clone(),
                        reason: need("--reason")?,
                    },
                )?;
                println!("device `{name}` revoked");
            }
            _ => {
                return Err(
                    "usage: byleave device --data DIR [enrol NAME [--recover] | revoke NAME \
                     --reason TEXT]"
                        .into(),
                );
            }
        },
        "withdraw" => {
            let [action] = pos.as_slice() else {
                return Err("usage: byleave withdraw --data DIR ACTION --reason TEXT".into());
            };
            ask(
                &data,
                HumanRequest::WithdrawApproval {
                    action: action.clone(),
                    reason: need("--reason")?,
                },
            )?;
            println!("approval withdrawn: the action is rejected");
        }
        _ => return Err(USAGE.into()),
    }
    Ok(())
}

/// `byleave verify`: through the kernel when it runs, else from the log
/// itself, read only, so a log the kernel refuses can still be checked.
fn verify(args: &[String]) -> Result<(), String> {
    let data = data_dir(args)?;
    let report = match ask(&data, HumanRequest::Verify) {
        Ok(r) => r,
        Err(e) if e.starts_with("the log was altered") => return Err(e),
        Err(_) => serde_json::to_value(
            by_your_leave::log::verify(data.join("log.db"))
                .map_err(|e| format!("the log was altered: {e}"))?,
        )
        .map_err(|e| e.to_string())?,
    };
    match report["chained_from"].as_u64() {
        Some(1) => println!(
            "the log holds together: {} events, each chained to the one before",
            report["events"]
        ),
        Some(n) => println!(
            "the log holds together: {} events, chained from event {n}; the {} before it \
             were written before the chain began",
            report["events"],
            n - 1
        ),
        None => println!(
            "the log holds {} events, none of them chained yet",
            report["events"]
        ),
    }
    match report["signatures"].as_u64() {
        Some(0) | None => {}
        Some(1) => println!("1 device signature checked against the keys enrolled in it"),
        Some(n) => println!("{n} device signatures checked against the keys enrolled in it"),
    }
    Ok(())
}

/// One adapter and the network it declares (D-77): recorded, not enforced.
fn adapter_line(a: &AdapterView) -> String {
    let sandboxed = if a.sandbox { ", sandboxed" } else { "" };
    let network = match a.network.as_deref() {
        None => "network not declared".to_owned(),
        Some([]) => "no network".to_owned(),
        Some(d) => format!("reaches {}", d.join(", ")),
    };
    format!("{} adapter `{}`{sandboxed}: {network}", a.kind, a.name)
}

/// `1 model call`, `2 model calls`.
fn count(n: u64, one: &str, many: &str) -> String {
    format!("{n} {}", if n == 1 { one } else { many })
}

/// The lines two texts differ by, with two lines of context around each
/// change: `-` the old text, `+` the new.
fn print_diff(old: &str, new: &str) {
    for line in diff_lines(old, new) {
        println!("    {line}");
    }
}

fn diff_lines(old: &str, new: &str) -> Vec<String> {
    let mut out = Vec::new();
    let (a, b): (Vec<&str>, Vec<&str>) = (old.lines().collect(), new.lines().collect());
    // The longest common subsequence of lines, by dynamic programming.
    let mut lcs = vec![vec![0usize; b.len() + 1]; a.len() + 1];
    for i in (0..a.len()).rev() {
        for j in (0..b.len()).rev() {
            lcs[i][j] = if a[i] == b[j] {
                lcs[i + 1][j + 1] + 1
            } else {
                lcs[i + 1][j].max(lcs[i][j + 1])
            };
        }
    }
    let mut ops: Vec<(char, &str)> = Vec::new();
    let (mut i, mut j) = (0, 0);
    while i < a.len() || j < b.len() {
        if i < a.len() && j < b.len() && a[i] == b[j] {
            ops.push((' ', a[i]));
            i += 1;
            j += 1;
        } else if j < b.len() && (i == a.len() || lcs[i][j + 1] > lcs[i + 1][j]) {
            ops.push(('+', b[j]));
            j += 1;
        } else {
            ops.push(('-', a[i]));
            i += 1;
        }
    }
    let near = |k: usize| {
        ops[k.saturating_sub(2)..(k + 3).min(ops.len())]
            .iter()
            .any(|(op, _)| *op != ' ')
    };
    let mut skipped = false;
    for (k, (op, line)) in ops.iter().enumerate() {
        if near(k) {
            if skipped {
                out.push("...".to_owned());
                skipped = false;
            }
            out.push(format!("{op} {line}"));
        } else {
            skipped = true;
        }
    }
    out
}

fn print_effects(effects: &Value, depth: usize) {
    for e in effects.as_array().into_iter().flatten() {
        println!("{}{}", "  ".repeat(depth), event_line(&e["event"]));
        print_effects(&e["effects"], depth + 1);
    }
}

fn print_tree(t: &Value, depth: usize) {
    let pad = "  ".repeat(depth);
    let g = &t["goal"];
    println!(
        "{pad}goal {}  {}  [{}]\n{pad}  {}",
        g["id"].as_str().unwrap_or("?"),
        g["status"].as_str().unwrap_or("?"),
        g["pack"].as_str().unwrap_or("?"),
        g["description"].as_str().unwrap_or("")
    );
    for task in t["tasks"].as_array().into_iter().flatten() {
        let after: Vec<&str> = task["after"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|a| a.as_str())
            .collect();
        println!(
            "{pad}  task `{}` ({})  {}, {} events{}",
            task["item"].as_str().unwrap_or("?"),
            task["role"].as_str().unwrap_or("?"),
            task["status"].as_str().unwrap_or("?"),
            task["events"],
            if after.is_empty() {
                String::new()
            } else {
                format!(", after {}", after.join(", "))
            }
        );
    }
    for child in t["goals"].as_array().into_iter().flatten() {
        print_tree(child, depth + 1);
    }
}

fn print_replay(r: &Value) {
    println!(
        "replay {} of invocation {}, on model `{}`",
        r["id"].as_str().unwrap_or("?"),
        r["invocation"].as_str().unwrap_or("?"),
        r["model"].as_str().unwrap_or("?")
    );
    match r["identical"].as_bool() {
        Some(true) => {
            println!("  on the recorded responses: every model request was the recorded one")
        }
        Some(false) => {
            println!("  on the recorded responses: the requests differed from the record")
        }
        None => {}
    }
    println!(
        "  {}, ${:.6}",
        count(
            r["calls"].as_array().map_or(0, |c| c.len()) as u64,
            "model call",
            "model calls"
        ),
        r["cost_micros"].as_u64().unwrap_or(0) as f64 / 1e6
    );
    if let Some(e) = r["error"].as_str() {
        println!("  no proposal: {e}");
    } else {
        println!("  proposed (not acted on): {}", r["proposal"]);
    }
    println!(
        "  originally: {} {}",
        r["original"]["type"].as_str().unwrap_or("?"),
        r["original"]["payload"]
    );
    println!();
}

fn parse<T: serde::de::DeserializeOwned>(v: Value) -> Result<T, String> {
    serde_json::from_value(v).map_err(|e| format!("the kernel sent an unexpected answer: {e}"))
}

fn actor_name(actor: &Value) -> String {
    match actor["kind"].as_str().or_else(|| actor.as_str()) {
        Some(k) => match actor["name"].as_str() {
            Some(n) => format!("{k}:{n}"),
            None => k.to_owned(),
        },
        None => actor.to_string(),
    }
}

fn event_line(e: &Value) -> String {
    format!(
        "{:>5}  {:<22} {:<22} {:<13} {}",
        e["seq"],
        e["event_type"].as_str().unwrap_or("?"),
        actor_name(&e["actor"]),
        e["trust"].as_str().unwrap_or("?"),
        serde_json::to_string(&e["payload"]).unwrap_or_default()
    )
}

fn print_escalation(v: &EscalationView, raw: bool) {
    println!("escalation {} ({})", v.id, v.kind);
    println!("  {}", v.question);
    // A question of the two quoting kinds logged before D-96 holds a role's
    // words: labelled as in the view before signing.
    if let Some(note) = by_your_leave_approval::question_note(&v.kind, &v.quoted) {
        println!("  {note}");
    }
    // Another party's words the kernel quotes, apart from its own (D-96).
    for q in &v.quoted {
        println!(
            "  quoted, a role's words and not the kernel's: {}",
            by_your_leave_approval::escape_direction(&serde_json::to_string(q).unwrap_or_default())
        );
    }
    if let Some(tool) = &v.tool {
        println!("  tool: {tool}");
    }
    if let Some(args) = &v.arguments {
        println!(
            "  arguments: {}",
            serde_json::to_string_pretty(args)
                .unwrap_or_default()
                .replace('\n', "\n  ")
        );
    }
    if let (Some(c), Some(b)) = (v.class, &v.basis) {
        println!("  class {c}: {b}");
    }
    if !v.options.is_empty() {
        println!("  options: {}", v.options.join(" | "));
    }
    println!("  events behind it:");
    for e in &v.events {
        if raw {
            println!(
                "    {}",
                serde_json::to_string_pretty(e)
                    .unwrap_or_default()
                    .replace('\n', "\n    ")
            );
        } else {
            println!("    {}", event_line(e));
        }
    }
    println!();
}

/// The budgets `open` and `reopen` name (D-80).
fn root_budgets(args: &[String]) -> Result<RootBudgets, String> {
    let number = |name: &str| -> Result<Option<u64>, String> {
        flag(args, name)
            .map(|v| {
                v.parse::<u64>()
                    .map_err(|_| format!("{name} needs a whole number, 0 or more"))
            })
            .transpose()
    };
    Ok(RootBudgets {
        spend_micros: number("--spend-micros")?,
        model_calls: number("--model-calls")?,
        actions: number("--actions")?,
    })
}

fn open_roots_any(b: &RootBudgets) -> bool {
    b.spend_micros.is_some() || b.model_calls.is_some() || b.actions.is_some()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_diff_shows_the_changed_lines_with_two_lines_around_them() {
        let old = "a\nb\nc\nd\ne\nf\ng\nh\n";
        let new = "a\nb\nc\nd\nE\nf\ng\nh\nI\n";
        assert_eq!(
            diff_lines(old, new),
            [
                "...", "  c", "  d", "- e", "+ E", "  f", "  g", "  h", "+ I"
            ]
        );
        assert!(diff_lines("same\n", "same\n").is_empty());
    }

    #[test]
    fn one_is_singular() {
        assert_eq!(count(1, "model call", "model calls"), "1 model call");
        assert_eq!(count(2, "model call", "model calls"), "2 model calls");
        assert_eq!(count(0, "action", "actions"), "0 actions");
    }
}