deedar-cli 0.5.0

Operator path: deedar create/get/list/trail/evidence/delete/leave/timestamp/current/migrate
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
//! Operator path: create, get, list, trail, evidence, delete, leave, timestamp, current, migrate.

use std::env;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use deed::{Body, Deed, DeedId, FormField, Grant, Kind, MailMessageId, Measure, Source, Step};
use deedar::{Client, CreateRequest, StoreUrl};

fn main() -> ExitCode {
    match dispatch(env::args().skip(1).collect()) {
        Ok(report) => {
            print!("{}", report.text);
            if report.ok {
                ExitCode::SUCCESS
            } else {
                ExitCode::from(1)
            }
        }
        Err(e) => {
            eprintln!("deedar: {e}");
            ExitCode::from(1)
        }
    }
}

/// What a verb produced: text to print, and whether the run succeeded. A set
/// check prints its report and exits non-zero.
struct Report {
    text: String,
    ok: bool,
}

/// Route the verbs that report per-id, and hand the rest to [`run`].
fn dispatch(args: Vec<String>) -> Result<Report, String> {
    // Before the store is resolved: asking which build this is must work on a
    // machine that has no store yet, and it is how anything checking for drift
    // finds out.
    if args.iter().any(|a| a == "--version" || a == "-V") {
        return Ok(Report {
            text: format!(
                "deedar {}
",
                env!("CARGO_PKG_VERSION")
            ),
            ok: true,
        });
    }
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Ok(Report {
            text: help_text(&args),
            ok: true,
        });
    }
    let (url, rest) = take_url(&args)?;
    if rest.first().map(String::as_str) == Some("evidence") && is_many(&rest[1..]) {
        return evidence_many(&url, &rest[1..]);
    }
    if rest.first().map(String::as_str) == Some("current") && is_many(&rest[1..]) {
        return current_many(&url, &rest[1..]);
    }
    run(args).map(|text| Report { text, ok: true })
}

/// Whether an `evidence` call names more than one deed; `-` reads ids from
/// stdin, one per line. A bare call is an error, not a wait on a terminal.
fn is_many(args: &[String]) -> bool {
    args.len() > 1 || args.first().is_some_and(|a| a == "-")
}

/// Check every named deed, one line each; one failure fails the list.
fn ids_from(args: &[String], verb: &str) -> Result<Vec<String>, String> {
    let ids: Vec<String> = if args.first().is_some_and(|a| a == "-") {
        let mut buf = String::new();
        std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)
            .map_err(|e| format!("read ids from stdin: {e}"))?;
        buf.split_whitespace().map(str::to_string).collect()
    } else {
        args.to_vec()
    };
    if ids.is_empty() {
        return Err(format!("{verb} - read no ids"));
    }
    Ok(ids)
}

/// Follow every named deed to the tip of its supersede chain; non-zero when
/// any is stale or missing, so a hook can gate on it.
fn current_many(url: &str, args: &[String]) -> Result<Report, String> {
    let ids = ids_from(args, "current")?;
    let mut client = Client::open(url).map_err(|e| e.to_string())?;
    let mut text = String::new();
    let mut stale = 0usize;
    for raw in &ids {
        match client
            .resolve(raw)
            .and_then(|id| client.current(&id).map(|d| (id, d)))
        {
            Ok((id, tip)) => {
                if tip.id.to_string() == id.to_string() {
                    text.push_str(&format!("{id} current\n"));
                } else {
                    stale += 1;
                    text.push_str(&format!("{id} SUPERSEDED by {}\n", tip.id));
                }
            }
            Err(e) => {
                stale += 1;
                text.push_str(&format!("{raw} FAILED: {e}\n"));
            }
        }
    }
    text.push_str(&format!("{} of {} current\n", ids.len() - stale, ids.len()));
    Ok(Report {
        ok: stale == 0,
        text,
    })
}

fn evidence_many(url: &str, args: &[String]) -> Result<Report, String> {
    let ids = ids_from(args, "evidence")?;
    let mut client = Client::open(url).map_err(|e| e.to_string())?;
    let mut text = String::new();
    let mut verified = 0usize;
    for raw in &ids {
        match client
            .resolve(raw)
            .and_then(|id| client.evidence(&id).map(|ev| ev.deed_id))
        {
            Ok(id) => {
                verified += 1;
                text.push_str(&format!("{id} ok\n"));
            }
            // The id as the caller wrote it, not as the store would spell it:
            // an id that does not resolve has no other spelling, and the
            // caller has to find this one in whatever cited it.
            Err(e) => text.push_str(&format!("{raw} FAILED: {e}\n")),
        }
    }
    text.push_str(&format!("{verified} of {} verified\n", ids.len()));
    Ok(Report {
        ok: verified == ids.len(),
        text,
    })
}

/// Sign a satchel's manifest, or check the signature on one against the
/// store's signer list. Without a list, the weaker answer is reported as such.
fn cmd_vouch(url: &str, args: &[String]) -> Result<String, String> {
    let dir = deedar::store_dir(url).map_err(|e| e.to_string())?;
    match args.first().map(String::as_str) {
        Some("sign") => {
            let path = PathBuf::from(args.get(1).ok_or("vouch sign needs a file")?);
            let out = deedar::vouch::sign(&path).map_err(|e| e.to_string())?;
            Ok(format!("{}\n", out.display()))
        }
        Some("check") => {
            let path = PathBuf::from(args.get(1).ok_or("vouch check needs a file")?);
            let policy = deedar::Policy::read(&dir).map_err(|e| e.to_string())?;
            let checked =
                deedar::vouch::check(&path, &policy.signers).map_err(|e| e.to_string())?;
            Ok(checked.render())
        }
        Some(other) => Err(format!("unknown vouch command {other}")),
        None => Err("vouch takes sign FILE or check FILE".into()),
    }
}

/// Check deeds somebody else handed over, with no store: every receipt against
/// the head in the bag. With `--since KEPT`, also that this log is the one
/// whose head the receiver kept last time, grown, by the bridge the bag
/// carries. With `--keep FILE`, record this bag's head for next time.
fn cmd_check(url: &str, args: &[String]) -> Result<String, String> {
    let mut dir: Option<PathBuf> = None;
    let mut since: Option<PathBuf> = None;
    let mut bridge_at: Option<PathBuf> = None;
    let mut keep: Option<PathBuf> = None;
    let mut at = 0;
    while at < args.len() {
        let flag = args[at].as_str();
        let slot = match flag {
            "--since" => Some(&mut since),
            "--bridge" => Some(&mut bridge_at),
            "--keep" => Some(&mut keep),
            _ => None,
        };
        if let Some(slot) = slot {
            at += 1;
            let value = args.get(at).ok_or_else(|| format!("{flag} needs a file"))?;
            *slot = Some(PathBuf::from(value));
        } else if dir.is_none() {
            dir = Some(PathBuf::from(flag));
        } else {
            return Err(format!("check takes one directory, and also got {flag:?}"));
        }
        at += 1;
    }
    let dir = dir.ok_or("check needs a satchel directory")?;

    // The reader's signer list, from their own store; none means the weaker answer.
    let accept = deedar::store_dir(url)
        .ok()
        .and_then(|dir| deedar::Policy::read(&dir).ok())
        .map(|policy| policy.signers)
        .unwrap_or_default();
    let done = deedar::check_handover(&dir, &accept).map_err(|e| e.to_string())?;

    let mut out = String::new();
    if let Some(path) = since {
        let text = std::fs::read_to_string(&path)
            .map_err(|_| format!("no kept head at {}", path.display()))?;
        let kept = deedar::kept_head(&text).map_err(|e| e.to_string())?;
        let now = done
            .head
            .clone()
            .ok_or("no deeds travelled with this satchel, so there is no head to compare")?;
        let bridge_at = bridge_at.or_else(|| bridge_in(&dir));
        let bridge = match &bridge_at {
            Some(path) => {
                let text = std::fs::read_to_string(path)
                    .map_err(|_| format!("no bridge at {}", path.display()))?;
                Some(deedar::Bridge::parse(&text).map_err(|e| e.to_string())?)
            }
            None => None,
        };
        deedar::check_since(&kept, bridge.as_ref(), &now).map_err(|e| e.to_string())?;
        if kept == now {
            out.push_str("the log is the one you kept, with nothing added\n");
        } else {
            out.push_str(&format!(
                "the log grew from the {} entries you kept to {} without dropping or rewriting one\n",
                kept.size, now.size
            ));
        }
    }
    out.push_str(&done.render());
    if let Some(path) = keep {
        if let Some(head) = &done.head {
            std::fs::write(&path, format!("size={} root={}\n", head.size, head.root))
                .map_err(|e| format!("{}: {e}", path.display()))?;
            out.push_str(&format!(
                "kept this head in {}; pass it to --since next time\n",
                path.display()
            ));
        }
    }
    Ok(out)
}

/// The bridge a sender put in the bag, beside the deeds or at the top.
fn bridge_in(dir: &Path) -> Option<PathBuf> {
    [
        dir.join("bridge.txt"),
        dir.join("data").join("deeds").join("bridge.txt"),
    ]
    .into_iter()
    .find(|path| path.is_file())
}

/// Write deeds into a satchel with the inclusion proof they were logged here
/// first. One accession, several, or `-` for stdin.
fn cmd_export(client: &mut Client, args: &[String]) -> Result<String, String> {
    let mut into: Option<PathBuf> = None;
    let mut rest: Vec<String> = Vec::new();
    let mut at = 0;
    while at < args.len() {
        match args[at].as_str() {
            "--into" => {
                at += 1;
                into = Some(PathBuf::from(
                    args.get(at).ok_or("--into needs a directory")?,
                ));
            }
            other => rest.push(other.to_string()),
        }
        at += 1;
    }
    let into = into.ok_or("export needs --into DIR")?;
    let ids = ids_from(&rest, "export")?;
    // Names resolve first; the exporter then borrows the store and reads the
    // log once for the whole list.
    let resolved: Vec<(String, deed::Result<DeedId>)> = ids
        .iter()
        .map(|raw| (raw.clone(), client.resolve(raw)))
        .collect();
    let exporter = client.exporter().map_err(|e| e.to_string())?;
    let mut wrote = 0usize;
    let mut refused = Vec::new();
    for (raw, id) in resolved {
        match id.and_then(|id| exporter.export(&id, &into)) {
            Ok(files) => wrote += files.len(),
            Err(e) => refused.push(format!("{raw}\t{e}")),
        }
    }
    if refused.is_empty() {
        return Ok(format!("exported {} deeds, {wrote} files\n", ids.len()));
    }
    // Asked for and not supplied is the receiver's problem to know about, so
    // it leaves on the error channel rather than in a line they have to spot.
    Err(format!(
        "{} of {} could not be exported:\n{}\n",
        refused.len(),
        ids.len(),
        refused.join("\n")
    ))
}

/// The append-only log: `head` to keep, `prove` for one deed, `bridge` from a
/// kept head to this one, `audit` of the log against the shelves.
fn cmd_log(client: &mut Client, args: &[String]) -> Result<String, String> {
    match args.first().map(String::as_str) {
        Some("head") | None => {
            // Signed when this store holds a key, because the head is the one
            // thing a reader keeps between visits and an unsigned one is two
            // numbers they were handed.
            if let Some(signed) = client.signed_head().map_err(|e| e.to_string())? {
                return Ok(signed.render());
            }
            let head = client.log_head().map_err(|e| e.to_string())?;
            Ok(format!("size={} root={}\n", head.size, head.root))
        }
        Some("list") => {
            let entries = client.log_entries().map_err(|e| e.to_string())?;
            let mut out = String::new();
            for (at, entry) in entries.iter().enumerate() {
                out.push_str(&format!(
                    "{at}\t{}\t{}\t{}\n",
                    entry.id, entry.digest, entry.unix_time
                ));
            }
            Ok(out)
        }
        Some("prove") => {
            let id = client
                .resolve(args.get(1).ok_or("log prove needs an id")?)
                .map_err(|e| e.to_string())?;
            // The same record an export writes beside a deed, so what is shown
            // here and what travels are one format and one checker.
            Ok(client.receipt(&id).map_err(|e| e.to_string())?.render())
        }
        Some("bridge") => {
            let from: usize = args
                .get(1)
                .ok_or("log bridge needs the size of the head the reader already holds")?
                .parse()
                .map_err(|_| "log bridge takes a size".to_string())?;
            Ok(client.bridge(from).map_err(|e| e.to_string())?.render())
        }
        Some("audit") => {
            let audit = client.log_audit().map_err(|e| e.to_string())?;
            if audit.is_clean() {
                return Ok(format!("ok {} logged and served\n", audit.logged));
            }
            let mut out = String::new();
            for row in &audit.missing {
                out.push_str(&format!("missing {}\t{}\n", row.id, row.why));
            }
            for id in &audit.unlogged {
                out.push_str(&format!("unlogged {id}\n"));
            }
            // Behind the log, not tampered with: say so.
            if audit.backfill_settles_it() {
                let older = if audit.predates_the_log() {
                    "this store predates the log"
                } else {
                    "this store fell behind the log"
                };
                out.push_str(&format!(
                    "nothing is missing and {} deeds are unlogged: {older}. \
                     `deedar log backfill` writes what is on the shelves, dated from the \
                     evidence where there is one.\n",
                    audit.unlogged.len()
                ));
            }
            Err(out)
        }
        Some("backfill") => {
            let added = client.log_backfill().map_err(|e| e.to_string())?;
            Ok(format!(
                "logged {} deeds already on the shelves\n",
                added.len()
            ))
        }
        Some(other) => Err(format!("unknown log command {other}")),
    }
}

fn run(args: Vec<String>) -> Result<String, String> {
    let (url, rest) = take_url(&args)?;
    let mut client = Client::open(&url).map_err(|e| e.to_string())?;
    match rest.first().map(String::as_str) {
        Some("host") if rest.get(1).map(String::as_str) == Some("accept") => {
            let layout = client.dir().join("layout");
            match client.accept_host_signer().map_err(|e| e.to_string())? {
                None => Err(
                    "host key: none; set DEEDAR_HOST_SIGNING_KEY or run `ljos onboard` first"
                        .into(),
                ),
                Some((public, true)) => Ok(format!(
                    "host key: {public}, added as a signer to {}\n",
                    layout.display()
                )),
                Some((public, false)) => Ok(format!(
                    "host key: {public}, already a signer {} lists\n",
                    layout.display()
                )),
            }
        }
        Some("host") if rest.len() > 1 => Err(format!(
            "host takes `accept` or nothing, not `{}`; `deedar host` says whether the layout lists the key",
            rest[1]
        )),
        Some("host") => {
            let layout = client.dir().join("layout");
            match (client.signer_public(), client.unaccepted_signer()) {
                (None, _) => Ok("host key: none; deeds carry no host signature\n".into()),
                (Some(public), None) => Ok(format!(
                    "host key: {public}, a signer {} lists\n",
                    layout.display()
                )),
                (Some(_), Some(public)) => Err(format!(
                    "host key {public} is not a signer {} lists; deeds signed now fail \
                     evidence until it carries `signer = {public}`; `deedar host accept` adds it",
                    layout.display()
                )),
            }
        }
        Some("create") => {
            let made = cmd_create(&mut client, &rest[1..]);
            if made.is_ok() {
                if let Some(public) = client.unaccepted_signer() {
                    eprintln!("{}", unaccepted_signer_warning(&public, client.dir()));
                }
            }
            made
        }
        Some("get") => {
            let id = client
                .resolve(rest.get(1).ok_or("get needs an id")?)
                .map_err(|e| e.to_string())?;
            let d = client.get(&id).map_err(|e| e.to_string())?;
            Ok(format_one(&d))
        }
        Some("list") => {
            let rows = client.list().map_err(|e| e.to_string())?;
            Ok(format_list(&rows))
        }
        Some("trail") => {
            let id = client
                .resolve(rest.get(1).ok_or("trail needs an id")?)
                .map_err(|e| e.to_string())?;
            let rows = client.trail(&id).map_err(|e| e.to_string())?;
            Ok(format_list(&rows))
        }
        Some("evidence") => {
            let id = client
                .resolve(rest.get(1).ok_or("evidence needs an id")?)
                .map_err(|e| e.to_string())?;
            let ev = client.evidence(&id).map_err(|e| e.to_string())?;
            Ok(format!(
                "id={} ok\nproducedBy={} {}\ntime={}\n",
                ev.deed_id,
                ev.produced_by.agent_id,
                ev.produced_by.activity_id.as_deref().unwrap_or("-"),
                ev.unix_time,
            ))
        }
        Some("delete") => {
            let id = client
                .resolve(rest.get(1).ok_or("delete needs an id")?)
                .map_err(|e| e.to_string())?;
            client.delete(&id).map_err(|e| e.to_string())?;
            Ok(format!("deleted {id}\n"))
        }
        Some("leave") => {
            let id = client
                .resolve(rest.get(1).ok_or("leave needs an id")?)
                .map_err(|e| e.to_string())?;
            let dest = PathBuf::from(rest.get(2).ok_or("leave needs a dest dir")?);
            let out = client.leave(&id, &dest).map_err(|e| e.to_string())?;
            Ok(format!("{}\n", out.display()))
        }
        Some("timestamp") => {
            let id = client
                .resolve(rest.get(1).ok_or("timestamp needs an id")?)
                .map_err(|e| e.to_string())?;
            let path = client.timestamp(&id).map_err(|e| e.to_string())?;
            Ok(format!("timestamp {}\n", path.display()))
        }
        Some("current") => {
            let id = client
                .resolve(rest.get(1).ok_or("current needs an id")?)
                .map_err(|e| e.to_string())?;
            let d = client.current(&id).map_err(|e| e.to_string())?;
            Ok(format_one(&d))
        }
        Some("log") => cmd_log(&mut client, &rest[1..]),
        Some("export") => cmd_export(&mut client, &rest[1..]),
        Some("check") => cmd_check(&url, &rest[1..]),
        Some("vouch") => cmd_vouch(&url, &rest[1..]),
        Some("migrate") => {
            client.migrate().map_err(|e| e.to_string())?;
            Ok("layout=1\n".into())
        }
        Some("url") => Ok(format!(
            "{}\n",
            StoreUrl::parse(&url).map_err(|e| e.to_string())?.as_url()
        )),
        Some(other) => Err(format!("unknown command {other}")),
        None => Err(usage().trim_end().to_string()),
    }
}

fn usage() -> String {
    "usage: deedar [--url FILE] create|get|list|trail|evidence|delete|leave|timestamp|current|log|export|check|vouch|migrate|host\n\
     deedar --help            this page\n\
     deedar create --help     kinds and flags, including --path\n\
     evidence, current and export take one id, several ids, or - to read them from stdin\n\
     log takes head, list, audit, backfill, prove ID, or bridge SIZE\n\
     check takes a satchel directory, --since KEPT_HEAD, --bridge FILE and --keep FILE; vouch takes sign FILE or check FILE\n\
     host says whether the store's layout lists the host signing key, and exits 1 when it does not\n\
     host accept adds the host signing key to the layout as a signer, and leaves every other line\n"
        .into()
}

fn help_text(args: &[String]) -> String {
    let verb = args
        .iter()
        .map(String::as_str)
        .find(|a| !a.starts_with('-') && *a != "--url");
    match verb {
        Some("create") => create_help(),
        _ => usage(),
    }
}

fn create_help() -> String {
    "deedar create KIND --agent WHO [flags]\n\
     kinds: file set quote patch maildraft clip page form table procedure event\n\
     create file wants --path FILE and --agent WHO\n\
     create set wants --member PATH (repeatable) and --agent WHO\n\
     --name NAME     defaults to the kind\n\
     --path FILE     the bytes for kind file (not --field path=)\n\
     --supersedes ID the deed this one revises\n\
     the same create again prints the deed it froze and exits 0; other bytes\n\
     under the same name are refused: revise with --name NAME-v2 --supersedes ID\n\
     the last stdout line is accession=ID: cite that ID, not the file= line\n"
        .into()
}

/// Where a seat keeps its store when nobody says otherwise.
///
/// `$XDG_DATA_HOME/deedar/store`, or `~/.local/share/deedar/store`.
fn default_store() -> Option<PathBuf> {
    let base = env::var_os("XDG_DATA_HOME")
        .map(PathBuf::from)
        .filter(|p| p.is_absolute())
        .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".local/share")))?;
    Some(base.join("deedar").join("store"))
}

/// The store to act on: `--url`, then `DEEDAR_URL`, then the seat's own if it
/// exists; an absent store refuses and names the path.
fn take_url(args: &[String]) -> Result<(String, Vec<String>), String> {
    let mut url = env::var("DEEDAR_URL").unwrap_or_default();
    let mut rest = Vec::new();
    let mut i = 0;
    while i < args.len() {
        if args[i] == "--url" {
            url = args.get(i + 1).ok_or("--url needs a value")?.clone();
            i += 2;
            continue;
        }
        rest.push(args[i].clone());
        i += 1;
    }
    if url.is_empty() {
        let seat = default_store();
        match seat {
            Some(dir) if dir.is_dir() => url = format!("file://{}", dir.display()),
            Some(dir) => {
                return Err(format!(
                    "set DEEDAR_URL or pass --url; no store at {}",
                    dir.display()
                ))
            }
            None => return Err("set DEEDAR_URL or pass --url".into()),
        }
    }
    Ok((url, rest))
}

/// What to tell a seat whose host signs with a key its store does not accept.
fn unaccepted_signer_warning(public: &str, store: &std::path::Path) -> String {
    format!(
        "deedar: warning: this deed is signed by {public}, which {}/layout does not list; \
         evidence will refuse it until that file carries `signer = {public}`; `deedar host accept` adds it",
        store.display()
    )
}

fn cmd_create(client: &mut Client, args: &[String]) -> Result<String, String> {
    let kind = args.first().ok_or("create needs a kind")?;
    let mut name = String::new();
    let mut id = None;
    let mut excerpt = String::new();
    let mut edition = String::new();
    let mut range_start = 0u64;
    let mut range_end = 0u64;
    let mut urls = Vec::new();
    let mut members = Vec::new();
    let mut tree = String::new();
    let mut diffs = Vec::new();
    let mut functionaries = Vec::new();
    let mut path = PathBuf::new();
    let mut message_id = String::new();
    let mut in_reply_to = None;
    let mut subject = String::new();
    let mut title = String::new();
    let mut agent = String::new();
    let mut activity = None;
    let mut grants = Vec::new();
    let mut sources = Vec::new();
    let mut media = None;
    let mut clip_sources = Vec::new();
    let mut in_point = 0.0f64;
    let mut out_point = 0.0f64;
    let mut duration = 0.0f64;
    let mut page_url = String::new();
    let mut snapshot = PathBuf::new();
    let mut blank = String::new();
    let mut fields = Vec::new();
    let mut measures = Vec::new();
    let mut steps = Vec::new();
    let mut when = String::new();
    let mut where_ = String::new();
    let mut who = String::new();
    let mut supersedes = None;
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "--help" | "-h" => return Ok(create_help()),
            "--name" => name = need(args, &mut i)?,
            "--id" => id = Some(DeedId::parse(&need(args, &mut i)?).map_err(|e| e.to_string())?),
            "--excerpt" => excerpt = need(args, &mut i)?,
            "--edition" => edition = need(args, &mut i)?,
            "--start" => range_start = need(args, &mut i)?.parse().map_err(|e| format!("{e}"))?,
            "--end" => range_end = need(args, &mut i)?.parse().map_err(|e| format!("{e}"))?,
            "--src-url" => urls.push(need(args, &mut i)?),
            "--member" => members.push(PathBuf::from(need(args, &mut i)?)),
            "--tree" => tree = need(args, &mut i)?,
            "--diff" => diffs.push(PathBuf::from(need(args, &mut i)?)),
            "--functionary" => functionaries.push(need(args, &mut i)?),
            "--path" => path = PathBuf::from(need(args, &mut i)?),
            "--media" => media = Some(need(args, &mut i)?),
            "--message-id" => message_id = need(args, &mut i)?,
            "--in-reply-to" => in_reply_to = Some(need(args, &mut i)?),
            "--subject" => subject = need(args, &mut i)?,
            "--title" => title = need(args, &mut i)?,
            "--agent" => agent = need(args, &mut i)?,
            "--activity" => activity = Some(need(args, &mut i)?),
            "--grant-host" => grants.push(Grant::Host(need(args, &mut i)?)),
            "--grant-path" => grants.push(Grant::Path(PathBuf::from(need(args, &mut i)?))),
            "--input" => {
                let mid = DeedId::parse(&need(args, &mut i)?).map_err(|e| e.to_string())?;
                sources.push(Source::deed(mid));
            }
            "--clip-src" => clip_sources.push(PathBuf::from(need(args, &mut i)?)),
            "--in" => in_point = need(args, &mut i)?.parse().map_err(|e| format!("{e}"))?,
            "--out" => out_point = need(args, &mut i)?.parse().map_err(|e| format!("{e}"))?,
            "--duration" => duration = need(args, &mut i)?.parse().map_err(|e| format!("{e}"))?,
            "--page-url" => page_url = need(args, &mut i)?,
            "--snapshot" => snapshot = PathBuf::from(need(args, &mut i)?),
            "--blank" => blank = need(args, &mut i)?,
            "--field" => {
                let raw = need(args, &mut i)?;
                let (n, v) = raw.split_once('=').ok_or("--field name=value")?;
                fields.push(FormField {
                    name: n.into(),
                    value: v.into(),
                });
            }
            "--measure" => {
                let raw = need(args, &mut i)?;
                let (n, v) = raw.split_once('=').ok_or("--measure name=value")?;
                measures.push(Measure {
                    name: n.into(),
                    value: v.into(),
                });
            }
            "--step" => steps.push(Step {
                text: need(args, &mut i)?,
                done: false,
            }),
            "--when" => when = need(args, &mut i)?,
            "--where" => where_ = need(args, &mut i)?,
            "--who" => who = need(args, &mut i)?,
            "--supersedes" => {
                supersedes = Some(DeedId::parse(&need(args, &mut i)?).map_err(|e| e.to_string())?)
            }
            other => return Err(format!("unknown create flag {other}")),
        }
        i += 1;
    }
    if agent.is_empty() {
        return Err("create wants --agent WHO".into());
    }
    if kind == "file" && path.as_os_str().is_empty() {
        return Err("create file wants --path FILE".into());
    }
    if name.is_empty() {
        name = kind.clone();
    }
    if edition.is_empty() && !urls.is_empty() {
        edition = urls[0].clone();
    }
    if range_end == 0 && !excerpt.is_empty() {
        range_end = excerpt.len() as u64;
    }
    let kind = Kind::parse(kind).map_err(|e| e.to_string())?;
    let body = match kind {
        Kind::File => Body::File {
            path,
            media_type: media,
        },
        Kind::Set => Body::Set {
            title: if title.is_empty() {
                name.clone()
            } else {
                title
            },
            members,
        },
        Kind::Quote => Body::Quote {
            edition,
            start: range_start,
            end: range_end,
            excerpt,
            urls,
        },
        Kind::Patch => Body::Patch {
            tree,
            diffs,
            functionaries: if functionaries.is_empty() {
                vec![agent.clone()]
            } else {
                functionaries
            },
        },
        Kind::MailDraft => Body::MailDraft {
            message_id: MailMessageId::parse(&message_id).map_err(|e| e.to_string())?,
            in_reply_to: in_reply_to
                .as_deref()
                .map(MailMessageId::parse)
                .transpose()
                .map_err(|e| e.to_string())?,
            subject,
            path,
        },
        Kind::Clip => Body::Clip {
            sources: clip_sources,
            in_point,
            out_point,
            duration,
            path,
        },
        Kind::Page => Body::Page {
            url: page_url,
            snapshot,
        },
        Kind::Form => Body::Form {
            blank,
            fields,
            path,
        },
        Kind::Table => Body::Table { measures },
        Kind::Procedure => Body::Procedure { steps },
        Kind::Event => Body::Event { when, where_, who },
    };
    let asked = name.clone();
    let (deed, _) = client
        .create(CreateRequest {
            id,
            name,
            sources,
            agent_id: agent,
            activity_id: activity,
            grants,
            body,
            supersedes,
        })
        .map_err(|e| frozen_hint(&e, &asked))?;
    // The last line is always the accession to cite: the kind lines above
    // end in a path or a digest, which no citation accepts.
    Ok(format!("{}accession={}\n", format_one(&deed), deed.id))
}

/// The create error as it reads, and on a frozen id what to run instead.
/// The same deed again is no error: the store hands it back. A frozen id
/// here differs from what the store has, so the revision needs a name of
/// its own and a `--supersedes` link to the deed it revises.
fn frozen_hint(e: &deed::Error, name: &str) -> String {
    match e {
        deed::Error::Frozen(id) => format!(
            "{e}; the store has {id} with other content, or it was deleted. \
             A revision takes a new name and points at the old deed: \
             --name {name}-v2 --supersedes {id}"
        ),
        _ => e.to_string(),
    }
}

fn need(args: &[String], i: &mut usize) -> Result<String, String> {
    let v = args.get(*i + 1).ok_or("flag needs a value")?;
    *i += 1;
    Ok(v.clone())
}

fn format_one(d: &Deed) -> String {
    let mut out = format!(
        "id={} kind={} name={}\npaths={}\nsources={}\nproducedBy={} {}\ngrants={}\nface={}\n",
        d.id,
        d.kind.token(),
        d.name,
        join_paths(&d.paths),
        join_sources(&d.sources),
        d.produced_by.agent_id,
        d.produced_by.activity_id.as_deref().unwrap_or("-"),
        join_grants(&d.grants),
        d.face.as_str(),
    );
    match &d.body {
        Body::Quote {
            excerpt,
            urls,
            edition,
            start,
            end,
        } => {
            out.push_str(&format!(
                "edition={edition} range={start}-{end}\nexcerpt={excerpt}\nquoteUrls={}\n",
                urls.join(",")
            ));
        }
        Body::Set { title, members } => {
            out.push_str(&format!("title={title}\nmembers={}\n", join_paths(members)));
        }
        Body::Patch {
            tree,
            diffs,
            functionaries,
        } => {
            out.push_str(&format!(
                "tree={tree}\ndiffs={}\nfunctionaries={}\n",
                join_paths(diffs),
                functionaries.join(",")
            ));
        }
        Body::MailDraft {
            message_id,
            in_reply_to,
            subject,
            ..
        } => {
            out.push_str(&format!(
                "messageId={}\ninReplyTo={}\nsubject={subject}\n",
                message_id.as_str(),
                in_reply_to
                    .as_ref()
                    .map(MailMessageId::as_str)
                    .unwrap_or("-"),
            ));
        }
        Body::File { path, .. } => {
            out.push_str(&format!("file={}\n", path.display()));
        }
        Body::Clip {
            in_point,
            out_point,
            duration,
            path,
            ..
        } => {
            out.push_str(&format!(
                "clip={} in={in_point} out={out_point} duration={duration}\n",
                path.display()
            ));
        }
        Body::Page { url, snapshot } => {
            out.push_str(&format!("page={url} snapshot={}\n", snapshot.display()));
        }
        Body::Form { blank, path, .. } => {
            out.push_str(&format!("form={blank} path={}\n", path.display()));
        }
        Body::Table { measures } => {
            out.push_str(&format!(
                "measures={}\n",
                measures
                    .iter()
                    .map(|m| format!("{}={}", m.name, m.value))
                    .collect::<Vec<_>>()
                    .join(",")
            ));
        }
        Body::Procedure { steps } => {
            out.push_str(&format!("steps={}\n", steps.len()));
        }
        Body::Event { when, where_, who } => {
            out.push_str(&format!("when={when} where={where_} who={who}\n"));
        }
    }
    out
}

fn format_list(rows: &[Deed]) -> String {
    let mut out = String::new();
    for d in rows {
        out.push_str(&format!("{}\n", d.label()));
        out.push_str(&format_one(d));
        out.push('\n');
    }
    out
}

fn join_paths(paths: &[PathBuf]) -> String {
    paths
        .iter()
        .map(|p| p.display().to_string())
        .collect::<Vec<_>>()
        .join(",")
}

fn join_sources(sources: &[Source]) -> String {
    sources
        .iter()
        .map(|s| match s {
            Source::Deed(id) => format!("deed:{id}"),
            Source::Path(p) => format!("path:{}", p.display()),
            Source::Url(u) => format!("url:{u}"),
        })
        .collect::<Vec<_>>()
        .join(",")
}

fn join_grants(grants: &[Grant]) -> String {
    grants
        .iter()
        .map(|g| match g {
            Grant::Host(h) => format!("host:{h}"),
            Grant::Path(p) => format!("path:{}", p.display()),
        })
        .collect::<Vec<_>>()
        .join(",")
}

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

    /// One test at a time over HOME, XDG_DATA_HOME and DEEDAR_URL.
    pub(super) static ENV: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Point HOME and XDG at a scratch directory for one closure.
    fn with_home<T>(
        dir: &std::path::Path,
        xdg: Option<&std::path::Path>,
        f: impl FnOnce() -> T,
    ) -> T {
        // Held across the set, the read and the restore. A lock taken only
        // around the set is a lock that guards nothing.
        let guard = ENV.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        let old_home = env::var_os("HOME");
        let old_xdg = env::var_os("XDG_DATA_HOME");
        let old_url = env::var_os("DEEDAR_URL");
        env::remove_var("DEEDAR_URL");
        env::set_var("HOME", dir);
        match xdg {
            Some(path) => env::set_var("XDG_DATA_HOME", path),
            None => env::remove_var("XDG_DATA_HOME"),
        }
        let out = f();
        match old_home {
            Some(v) => env::set_var("HOME", v),
            None => env::remove_var("HOME"),
        }
        match old_xdg {
            Some(v) => env::set_var("XDG_DATA_HOME", v),
            None => env::remove_var("XDG_DATA_HOME"),
        }
        if let Some(v) = old_url {
            env::set_var("DEEDAR_URL", v);
        }
        drop(guard);
        out
    }

    #[test]
    fn an_explicit_url_wins_over_everything() {
        let dir = tempfile::tempdir().unwrap();
        with_home(dir.path(), None, || {
            let args = vec![
                "--url".to_string(),
                "file:///somewhere".to_string(),
                "list".into(),
            ];
            let (url, rest) = take_url(&args).unwrap();
            assert_eq!(url, "file:///somewhere");
            assert_eq!(rest, vec!["list".to_string()]);
        });
    }

    #[test]
    fn the_seat_store_is_used_when_it_is_there() {
        let dir = tempfile::tempdir().unwrap();
        let store = dir.path().join(".local/share/deedar/store");
        std::fs::create_dir_all(&store).unwrap();
        with_home(dir.path(), None, || {
            let (url, _) = take_url(&["list".to_string()]).unwrap();
            assert_eq!(url, format!("file://{}", store.display()));
        });
    }

    #[test]
    fn xdg_moves_the_seat_store() {
        let dir = tempfile::tempdir().unwrap();
        let xdg = dir.path().join("data");
        let store = xdg.join("deedar/store");
        std::fs::create_dir_all(&store).unwrap();
        with_home(dir.path(), Some(&xdg), || {
            let (url, _) = take_url(&["list".to_string()]).unwrap();
            assert_eq!(url, format!("file://{}", store.display()));
        });
    }

    #[test]
    fn no_store_refuses_and_names_the_path_it_wanted() {
        // Creating one wherever a command happened to run is how a seat ends
        // up with two stores, and a citation resolving against one and not the
        // other is worse than a command that refused.
        let dir = tempfile::tempdir().unwrap();
        with_home(dir.path(), None, || {
            let err = take_url(&["list".to_string()]).unwrap_err();
            assert!(err.contains("no store at"), "{err}");
            assert!(err.contains(".local/share/deedar/store"), "{err}");
        });
    }
}

#[cfg(test)]
mod tests {
    use super::{dispatch, run};
    use std::time::{SystemTime, UNIX_EPOCH};

    /// The machine's own signing key, when it has one, would sign deeds
    /// into scratch stores that list no signer. The switch is set once, under
    /// the environment lock, before the first scratch store is handed out.
    fn keyless() {
        static OFF: std::sync::Once = std::sync::Once::new();
        OFF.call_once(|| {
            let _env = super::url_tests::ENV
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            std::env::set_var("DEEDAR_HOST_SIGNING_KEY", "off");
        });
    }

    fn tmp_url() -> String {
        keyless();
        let n = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("deedar-cli-{n}"));
        std::fs::create_dir_all(&dir).expect("dir");
        format!("file://{}", dir.display())
    }

    #[test]
    fn help_does_not_need_a_store() {
        let page = dispatch(vec!["--help".into()]).unwrap();
        assert!(page.ok);
        assert!(page.text.contains("deedar create --help"), "{}", page.text);
        let create = dispatch(vec!["create".into(), "--help".into()]).unwrap();
        assert!(create.text.contains("--path FILE"), "{}", create.text);
        let file = dispatch(vec!["create".into(), "file".into(), "--help".into()]).unwrap();
        assert!(
            file.text.contains("create file wants --path FILE"),
            "{}",
            file.text
        );
    }

    /// A misspelled `host` verb is refused, not read as the status check.
    #[test]
    fn host_refuses_a_verb_it_does_not_know() {
        let url = tmp_url();
        let said = run(vec!["--url".into(), url, "host".into(), "acept".into()]).unwrap_err();
        assert!(said.contains("host takes `accept` or nothing"), "{said}");
        assert!(said.contains("`acept`"), "{said}");
    }

    /// A rerun of the same create is a success; other bytes under the
    /// same name are refused with the flags for a revision.
    #[test]
    fn create_again_succeeds_on_the_same_bytes_and_names_a_revision_otherwise() {
        let url = tmp_url();
        let dir = std::path::PathBuf::from(url.trim_start_matches("file://"));
        let survey = dir.join("survey.md");
        std::fs::write(&survey, "first take\n").unwrap();
        let create = || {
            run(vec![
                "--url".into(),
                url.clone(),
                "create".into(),
                "file".into(),
                "--name".into(),
                "survey-md".into(),
                "--path".into(),
                survey.display().to_string(),
                "--agent".into(),
                "saddle".into(),
            ])
        };
        let first = create().expect("first create");
        let again = create().expect("same bytes again");
        assert_eq!(first, again);
        for out in [&first, &again] {
            assert_eq!(
                out.lines().last(),
                Some("accession=deed-file-survey-md"),
                "{out}"
            );
        }
        std::fs::write(&survey, "second take\n").unwrap();
        let err = create().expect_err("other bytes");
        assert!(err.contains("deed frozen: deed-file-survey-md"), "{err}");
        assert!(
            err.contains("--name survey-md-v2 --supersedes deed-file-survey-md"),
            "{err}"
        );
    }

    #[test]
    fn cli_creates_quote_and_gets_it() {
        let url = tmp_url();
        let quote = run(vec![
            "--url".into(),
            url.clone(),
            "create".into(),
            "quote".into(),
            "--id".into(),
            "deed-quote-rfc2094-nll".into(),
            "--name".into(),
            "NLL: lifetimes from the CFG".into(),
            "--excerpt".into(),
            "lifetimes that are based on the control-flow graph".into(),
            "--src-url".into(),
            "https://rust-lang.github.io/rfcs/2094-nll.html".into(),
            "--agent".into(),
            "reader".into(),
        ])
        .expect("create quote");
        assert!(quote.contains("deed-quote-rfc2094-nll"), "{quote}");
        assert!(quote.contains("kind=quote"), "{quote}");
        assert!(
            quote.contains("excerpt=lifetimes that are based on the control-flow graph"),
            "{quote}"
        );

        let got = run(vec![
            "--url".into(),
            url.clone(),
            "get".into(),
            "deed-quote-rfc2094-nll".into(),
        ])
        .expect("get");
        assert!(got.contains("deed-quote-rfc2094-nll"), "{got}");
        assert!(got.contains("kind=quote"), "{got}");
        assert!(
            got.contains("excerpt=lifetimes that are based on the control-flow graph"),
            "{got}"
        );

        let trail = run(vec![
            "--url".into(),
            url,
            "trail".into(),
            "deed-quote-rfc2094-nll".into(),
        ])
        .expect("trail");
        assert!(trail.contains("deed-quote-rfc2094-nll"), "{trail}");
    }

    /// A working set arrives as several ids at once, and the answer a caller
    /// needs is which of them failed rather than that one did.
    #[test]
    fn evidence_over_several_ids_reports_each_and_fails_on_any() {
        let url = tmp_url();
        for slug in ["deed-quote-first", "deed-quote-second"] {
            run(vec![
                "--url".into(),
                url.clone(),
                "create".into(),
                "quote".into(),
                "--id".into(),
                slug.into(),
                "--excerpt".into(),
                "a range in a frozen edition".into(),
                "--src-url".into(),
                "https://example.invalid/edition".into(),
                "--agent".into(),
                "reader".into(),
            ])
            .expect("create quote");
        }

        let both = dispatch(vec![
            "--url".into(),
            url.clone(),
            "evidence".into(),
            "deed-quote-first".into(),
            "deed-quote-second".into(),
        ])
        .expect("evidence over two ids");
        assert!(both.ok, "{}", both.text);
        assert!(both.text.contains("deed-quote-first ok"), "{}", both.text);
        assert!(both.text.contains("2 of 2 verified"), "{}", both.text);

        // One bad id in a set makes the set untrustworthy, and the report has
        // to name which one rather than stopping at it.
        let mixed = dispatch(vec![
            "--url".into(),
            url,
            "evidence".into(),
            "deed-quote-first".into(),
            "deed-quote-absent".into(),
            "deed-quote-second".into(),
        ])
        .expect("evidence over a set holding one bad id");
        assert!(!mixed.ok, "{}", mixed.text);
        assert!(
            mixed.text.contains("deed-quote-absent FAILED"),
            "{}",
            mixed.text
        );
        assert!(
            mixed.text.contains("deed-quote-second ok"),
            "a bad id must not stop the rest of the set: {}",
            mixed.text
        );
        assert!(mixed.text.contains("2 of 3 verified"), "{}", mixed.text);
    }

    /// A citation is written once and the thing it names can be superseded
    /// afterwards. Whatever holds the citations cannot notice that on its own,
    /// so the set form is what tells it which have moved on.
    #[test]
    fn current_over_a_set_names_the_ones_that_moved() {
        let url = tmp_url();
        let quote = |slug: &str, extra: Vec<String>| {
            let mut argv = vec![
                "--url".into(),
                url.clone(),
                "create".into(),
                "quote".into(),
                "--id".into(),
                slug.to_string(),
                "--excerpt".into(),
                "a range in a frozen edition".into(),
                "--src-url".into(),
                "https://example.invalid/edition".into(),
                "--agent".into(),
                "reader".into(),
            ];
            argv.extend(extra);
            run(argv).expect("create quote");
        };
        quote("deed-quote-stable", vec![]);
        quote("deed-quote-first", vec![]);
        quote(
            "deed-quote-second",
            vec!["--supersedes".into(), "deed-quote-first".into()],
        );

        let report = dispatch(vec![
            "--url".into(),
            url,
            "current".into(),
            "deed-quote-stable".into(),
            "deed-quote-first".into(),
        ])
        .expect("current over a set");
        assert!(!report.ok, "one of them moved: {}", report.text);
        assert!(
            report.text.contains("deed-quote-stable current"),
            "{}",
            report.text
        );
        assert!(
            report
                .text
                .contains("deed-quote-first SUPERSEDED by deed-quote-second"),
            "the citation has to name what to cite instead: {}",
            report.text
        );
        assert!(report.text.contains("1 of 2 current"), "{}", report.text);
    }

    /// One id is still the single-deed report it always was, so a caller that
    /// parses that output keeps working.
    #[test]
    fn evidence_over_one_id_keeps_its_own_shape() {
        let url = tmp_url();
        run(vec![
            "--url".into(),
            url.clone(),
            "create".into(),
            "quote".into(),
            "--id".into(),
            "deed-quote-alone".into(),
            "--excerpt".into(),
            "a range in a frozen edition".into(),
            "--src-url".into(),
            "https://example.invalid/edition".into(),
            "--agent".into(),
            "reader".into(),
        ])
        .expect("create quote");

        let one = dispatch(vec![
            "--url".into(),
            url,
            "evidence".into(),
            "deed-quote-alone".into(),
        ])
        .expect("evidence over one id");
        assert!(one.ok);
        assert!(one.text.contains("id=deed-quote-alone ok"), "{}", one.text);
        assert!(
            !one.text.contains("verified"),
            "the single-deed report has no set summary: {}",
            one.text
        );
    }

    #[test]
    fn cli_get_accepts_deed_digest() {
        let url = tmp_url();
        let created = run(vec![
            "--url".into(),
            url.clone(),
            "create".into(),
            "quote".into(),
            "--id".into(),
            "deed-quote-digest-alias".into(),
            "--name".into(),
            "digest alias".into(),
            "--excerpt".into(),
            "canonical bytes have a digest".into(),
            "--src-url".into(),
            "https://example.com/digest".into(),
            "--agent".into(),
            "reader".into(),
        ])
        .expect("create quote");
        assert!(created.contains("deed-quote-digest-alias"), "{created}");

        let mut client = deedar::Client::open(&url).expect("open");
        let deed = client
            .get(&deed::DeedId::parse("deed-quote-digest-alias").unwrap())
            .expect("load");
        let digest = deedar::deed_digest(&deed);
        let got = run(vec!["--url".into(), url, "get".into(), digest]).expect("get digest");
        assert!(got.contains("deed-quote-digest-alias"), "{got}");
        assert!(
            got.contains("excerpt=canonical bytes have a digest"),
            "{got}"
        );
    }

    #[test]
    fn cli_evidence_accepts_a_created_file() {
        let url = tmp_url();
        let dir = std::path::PathBuf::from(url.trim_start_matches("file://"));
        let letter = dir.join("letter.pdf");
        std::fs::write(&letter, b"%PDF-letter").expect("blob");
        run(vec![
            "--url".into(),
            url.clone(),
            "create".into(),
            "file".into(),
            "--id".into(),
            "deed-file-letter".into(),
            "--name".into(),
            "Hospital letter".into(),
            "--path".into(),
            letter.display().to_string(),
            "--media".into(),
            "application/pdf".into(),
            "--agent".into(),
            "reader".into(),
        ])
        .expect("create file");
        let ev = run(vec![
            "--url".into(),
            url,
            "evidence".into(),
            "deed-file-letter".into(),
        ])
        .expect("evidence");
        assert!(ev.contains("id=deed-file-letter"), "{ev}");
        assert!(ev.contains("ok"), "{ev}");
        assert!(ev.contains("producedBy=reader"), "{ev}");
    }
}