stratum-node-cli 0.1.0-alpha.4

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
//! `stratum app …`: a member's applications, through the gate. The
//! catalogue, installing with the ACL preview, conditional writes and
//! read-back, the installation reads, manual runs, withdrawal with its ACL
//! cleanup, and resume after a restore.

use std::collections::HashMap;
use std::fmt::Write as _;

use serde::de::DeserializeOwned;
use serde_json::{json, Value as Json};
use stratum_node_core::{
    check_schedule_secs, render_offered, ApplicationId, Catalogue, CatalogueEntry, CleanupRequest,
    CleanupResponse, ConsentRequest, ConsentResponse, ContainerPath, CreateInstallationRequest,
    CreateInstallationResponse, DidNostr, GrantState, InstallationActionRequest, InstallationId,
    InstallationList, InstallationState, InstallationView, JobList, NostrSecretKey, OfferedGrant,
    PodPath, ResumeInstallationResponse, RunRequest, RunResponse, WithdrawResponse, WorkspaceMode,
};

use crate::acl::{self, AclDocument, Authorisation, Governing};
use crate::client::MAX_RESPONSE_BYTES;
use crate::error::CliError;
use crate::exit;
use crate::gate::{GateClient, Precondition, Request, Route, ANY, JSON};
use crate::origin::GateTarget;
use crate::output::sanitize;
use crate::session::{operation_id, to_body, Confirmation, Session};

/// `GET` route: the catalogue of approved applications.
const CATALOGUE: &str = "/api/v1/catalogue";
/// The installations route; each installation is `INSTALLATIONS/<id>`.
const INSTALLATIONS: &str = "/api/v1/installations";
/// The media type an ACL is written with.
const TURTLE: &str = "text/turtle";
/// The largest ACL read.
const MAX_ACL_BYTES: u64 = 1024 * 1024;
/// How many times one container's write starts again from its read, after
/// the governing ACL changed or a conditional write lost a race.
pub(crate) const MAX_ACL_ATTEMPTS: u32 = 5;

/// The statement `app install` prints before it asks (ADR D12, contract
/// "The client previews").
///
/// # Examples
///
/// ```
/// assert!(stratum_node_cli::OPERATOR_STATEMENT.contains("root on the host"));
/// ```
pub const OPERATOR_STATEMENT: &str = "The node's operator has root on the host: they can read \
     workspaces, the tenant daemon's data (where this application's containers run) and backups, \
     which hold your pod. Stratum states this; it does not prevent it.";

/// Options for [`Session::app_install`].
///
/// # Examples
///
/// ```
/// use stratum_node_cli::{Confirmation, InstallOptions};
/// use stratum_node_core::WorkspaceMode;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // `stratum app install <application> --schedule 3600 --yes`
/// let options = InstallOptions {
///     application: "0123456789abcdef0123456789abcdef".parse()?,
///     schedule_secs: 3600,
///     workspace: WorkspaceMode::None,
///     operation_id: None,
///     confirmation: Confirmation::Assumed,
/// };
/// assert_eq!(options.schedule_secs, 3600);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct InstallOptions {
    /// The application to install, as the catalogue lists it.
    pub application: ApplicationId,
    /// The schedule interval in seconds: 0 for manual runs only, otherwise
    /// 300 to 604800.
    pub schedule_secs: u64,
    /// The workspace asked for; no more than the manifest allows. Every mode
    /// other than `none` is refused by a node without workspace slots.
    pub workspace: WorkspaceMode,
    /// The operation ID of the create request; random when `None`. Pass the
    /// one a previous run printed, with the same application, schedule and
    /// workspace, to continue that installation rather than create another.
    pub operation_id: Option<String>,
    /// Whether to ask before writing the grant.
    pub confirmation: Confirmation,
}

/// One container of an install: what governs it now and the ACL the client
/// would write.
#[derive(Debug, Clone)]
struct Planned {
    /// The granted container.
    container: PodPath,
    /// Its ACL.
    acl: PodPath,
    /// What governs the container now.
    fingerprint: Fingerprint,
    /// The container's own ACL, byte for byte, if it has one.
    previous: Option<Vec<u8>>,
    /// The new ACL's statements.
    document: AclDocument,
    /// The new ACL's text.
    text: String,
}

/// Which ACL governs a container, and its entity tag: what the reread
/// before a write compares.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Fingerprint {
    /// The container's own ACL.
    Own(String),
    /// An ancestor's ACL.
    Inherited(PodPath, String),
    /// A planned ancestor ACL of this install, not yet written.
    Planned(PodPath),
    /// No ACL.
    Nothing,
}

/// An ACL this run wrote, kept so it can be removed again.
#[derive(Debug, Clone)]
struct Written {
    /// The ACL path.
    acl: PodPath,
    /// The container's own ACL before the write, or `None` if the client
    /// created it.
    previous: Option<Vec<u8>>,
    /// The entity tag read back after the write.
    etag: String,
}

/// The result of a conditional `PUT`.
enum Put {
    /// Written.
    Done,
    /// 412: the condition did not hold.
    Lost,
}

/// A tenant's context for one command: the gate, the key and its DID.
struct Tenant<'a> {
    session: &'a Session,
    gate: GateClient,
    key: NostrSecretKey,
    owner: DidNostr,
}

impl Session {
    /// `stratum app catalogue`: lists the applications this node has
    /// approved, each with its manifest's name, version, image ID, granted
    /// containers and the most workspace it may be given. Signed.
    ///
    /// # Errors
    ///
    /// Key, transport, protocol and server errors (`suspended` while the
    /// membership is suspended).
    pub fn app_catalogue(&self, target: &GateTarget) -> Result<u8, CliError> {
        self.with_tenant(target, |tenant| {
            let (catalogue, raw): (Catalogue, Json) = tenant.get(CATALOGUE)?;
            self.output().json(&raw)?;
            if catalogue.applications.is_empty() {
                self.output()
                    .line("no applications are approved on this node")?;
            }
            for entry in &catalogue.applications {
                for line in describe_entry(entry) {
                    self.output().line(&line)?;
                }
            }
            Ok(exit::OK)
        })
    }

    /// `stratum app install <application> [--schedule <secs>] [--workspace
    /// none|read|write] [--yes]`: installs an application in the caller's
    /// pod. Signed.
    ///
    /// 1. Reads the catalogue entry, and creates the installation
    ///    (`pending_consent`), which gives the application's key and the
    ///    offered grant.
    /// 2. Renders the grant again from the manifest with
    ///    [`render_offered`] and refuses unless every byte and hash matches
    ///    the offer.
    /// 3. For each granted container, reads the ACL that governs it now
    ///    (its own, or the nearest ancestor's) and builds its new ACL: the
    ///    owner's control, every rule of its own ACL unchanged, inherited
    ///    `acl:default` rules materialised, `acl:accessTo`-only ones not
    ///    copied, and the offered rule. A statement the client does not
    ///    evaluate is refused, and the application is never given
    ///    `Control`.
    /// 4. Prints the diff of each ACL, the owner, the application, its
    ///    version and image ID and [`OPERATOR_STATEMENT`], and asks.
    /// 5. For each container: checks the installation is still
    ///    `pending_consent`, rereads the governing ACL and starts again if
    ///    its entity tag changed, writes with `If-Match` (or
    ///    `If-None-Match: *` when the container had no ACL), starts again on
    ///    412, and reads the ACL back, comparing parsed statements.
    /// 6. Sends consent only if every read-back matched. On a mismatch, a
    ///    refused consent or an installation that is no longer
    ///    `pending_consent`, removes what it wrote.
    ///
    /// The operation ID of the create request is printed first; declining
    /// leaves the installation `pending_consent` with nothing written.
    ///
    /// # Errors
    ///
    /// [`CliError::Usage`] for a schedule out of range, a workspace above
    /// the manifest's or an application not in the catalogue;
    /// [`CliError::NotConfirmed`]; [`CliError::Refused`] for an offer that
    /// is not the one the manifest renders, or an ACL that would give the
    /// application `Control`; [`CliError::AclNotEvaluated`];
    /// [`CliError::ReadBackMismatch`]; [`CliError::ConsentRefused`]; and
    /// key, transport, protocol and server errors (`workspace_unavailable`,
    /// `application_unavailable`, `precondition_failed` when a container
    /// kept changing).
    pub fn app_install(
        &self,
        target: &GateTarget,
        options: &InstallOptions,
    ) -> Result<u8, CliError> {
        check_schedule_secs(options.schedule_secs).map_err(|_| {
            CliError::Usage(
                "--schedule must be 0 (manual runs only) or 300 to 604800 seconds".to_owned(),
            )
        })?;
        let operation = operation_id(options.operation_id.as_deref())?;
        self.with_tenant(target, |tenant| tenant.install(options, &operation))
    }

    /// `stratum app list`: lists the caller's installations with their
    /// state, grant and job counts, and any ACL cleanup still pending.
    /// Signed.
    ///
    /// # Errors
    ///
    /// Key, transport, protocol and server errors.
    pub fn app_list(&self, target: &GateTarget) -> Result<u8, CliError> {
        self.with_tenant(target, |tenant| {
            let (list, raw): (InstallationList, Json) = tenant.get(INSTALLATIONS)?;
            for view in &list.installations {
                if view.owner != tenant.owner {
                    return Err(CliError::Refused(format!(
                        "the node listed installation {} of {} among yours",
                        view.installation, view.owner
                    )));
                }
            }
            self.output().json(&raw)?;
            if list.installations.is_empty() {
                self.output().line("no installations")?;
            }
            for view in &list.installations {
                self.output().line(&summary_line(view))?;
            }
            Ok(exit::OK)
        })
    }

    /// `stratum app show <installation>`: prints one installation: state,
    /// application and key, schedule, workspace, key-disable reasons, grant
    /// and pending cleanup, the enforcement parts while a withdrawal or
    /// suspension is being enforced, and job counts. Signed.
    ///
    /// # Errors
    ///
    /// [`CliError::Refused`] for an answer naming another installation or
    /// owner, and key, transport, protocol and server errors.
    pub fn app_show(
        &self,
        target: &GateTarget,
        installation: &InstallationId,
    ) -> Result<u8, CliError> {
        self.with_tenant(target, |tenant| {
            let (view, raw) = tenant.installation(installation)?;
            self.output().json(&raw)?;
            for line in describe_view(&view) {
                self.output().line(&line)?;
            }
            Ok(exit::OK)
        })
    }

    /// `stratum app jobs <installation>`: lists the installation's jobs:
    /// period, state, attempts, outcome and the result the job reported.
    /// Signed.
    ///
    /// # Errors
    ///
    /// Key, transport, protocol and server errors.
    pub fn app_jobs(
        &self,
        target: &GateTarget,
        installation: &InstallationId,
    ) -> Result<u8, CliError> {
        self.with_tenant(target, |tenant| {
            let path = format!("{INSTALLATIONS}/{installation}/jobs");
            let (jobs, raw): (JobList, Json) = tenant.get(&path)?;
            if jobs.installation != *installation {
                return Err(CliError::Refused(format!(
                    "asked for the jobs of {installation}, the node answered with {}",
                    jobs.installation
                )));
            }
            self.output().json(&raw)?;
            if jobs.jobs.is_empty() {
                self.output().line("no jobs")?;
            }
            for job in &jobs.jobs {
                let mut line = format!(
                    "period {}  {}  job {}  attempts {}",
                    job.period, job.state, job.job, job.attempts
                );
                if let Some(outcome) = job.outcome {
                    let _ = write!(line, "  outcome {outcome}");
                }
                if let Some(resource) = &job.resource {
                    let _ = write!(line, "  resource {}", sanitize(resource));
                }
                if let Some(sha256) = &job.sha256 {
                    let _ = write!(line, "  sha256 {sha256}");
                }
                if let Some(length) = job.length {
                    let _ = write!(line, "  {length} bytes");
                }
                if let Some(code) = job.exit_code {
                    let _ = write!(line, "  exit {code}");
                }
                if let Some(at) = job.next_eligible_at {
                    let _ = write!(line, "  next attempt after {at}");
                }
                self.output().line(&line)?;
            }
            Ok(exit::OK)
        })
    }

    /// `stratum app run <installation> --period <n> [--yes]`: creates the
    /// job for period `n` if none exists. Asks first. Signed. A period that
    /// already has a job answers that job.
    ///
    /// # Errors
    ///
    /// [`CliError::NotConfirmed`], and key, transport, protocol and server
    /// errors.
    pub fn app_run(
        &self,
        target: &GateTarget,
        installation: &InstallationId,
        period: u64,
        operation_id_arg: Option<&str>,
        confirmation: Confirmation,
    ) -> Result<u8, CliError> {
        let operation = operation_id(operation_id_arg)?;
        self.with_tenant(target, |tenant| {
            if !self.confirmed(
                &format!("run period {period} of installation {installation} now?"),
                confirmation,
            )? {
                return Err(CliError::NotConfirmed);
            }
            tenant.note_operation(&operation, "")?;
            let body = to_body(&RunRequest {
                operation_id: operation.clone(),
                period,
            })?;
            let (answer, _raw): (RunResponse, Json) =
                tenant.post(&format!("{INSTALLATIONS}/{installation}/run"), &body)?;
            self.output().json(&json!({
                "operation_id": operation.as_str(),
                "installation": installation,
                "period": period,
                "job": answer.job,
                "state": answer.state,
            }))?;
            self.output().line(&format!(
                "period {period}: job {} is {}",
                answer.job, answer.state
            ))?;
            Ok(exit::OK)
        })
    }

    /// `stratum app withdraw <installation> [--yes]`: withdraws the
    /// installation, then removes its authorisation from every granted
    /// container's ACL and reports the cleanup, as
    /// [`app_cleanup`](Self::app_cleanup) does. Asks first. Signed.
    ///
    /// The node answers at once with `authorisation: enforcing`: its gate
    /// and proxy refuse the key once they take the new revision, or within
    /// 310 s. The ACL cleanup is the member's part: if it is interrupted,
    /// every `stratum app` command shows it pending until
    /// `stratum app cleanup` finishes it.
    ///
    /// # Errors
    ///
    /// [`CliError::NotConfirmed`]; [`CliError::CleanupPending`] (or
    /// [`CliError::AclNotEvaluated`]) when a container's ACL could not be
    /// cleaned; key, transport, protocol and server errors (`suspended`
    /// while the membership is suspended).
    pub fn app_withdraw(
        &self,
        target: &GateTarget,
        installation: &InstallationId,
        operation_id_arg: Option<&str>,
        confirmation: Confirmation,
    ) -> Result<u8, CliError> {
        let operation = operation_id(operation_id_arg)?;
        self.with_tenant(target, |tenant| {
            let question = format!(
                "withdraw installation {installation}? Its key is disabled and its jobs stop; \
                 then its authorisation is removed from each granted container's ACL"
            );
            if !self.confirmed(&question, confirmation)? {
                return Err(CliError::NotConfirmed);
            }
            tenant.note_operation(&operation, "")?;
            let body = to_body(&InstallationActionRequest {
                operation_id: operation.clone(),
            })?;
            let (answer, raw): (WithdrawResponse, Json) =
                tenant.post(&format!("{INSTALLATIONS}/{installation}/withdraw"), &body)?;
            if answer.state != InstallationState::Withdrawn {
                return Err(CliError::Refused(format!(
                    "the node reports installation {installation} as {} after withdraw",
                    answer.state
                )));
            }
            self.output().line(&format!(
                "installation {installation}: withdrawn; authorisation {}",
                answer.authorisation
            ))?;
            let (view, _raw) = tenant.installation(installation)?;
            let report = tenant.cleanup(&view, &answer.cleanup_pending)?;
            self.output().json(&json!({
                "operation_id": operation.as_str(),
                "installation": installation,
                "withdraw": raw,
                "cleanup": report.json(),
            }))?;
            report.finish(installation)
        })
    }

    /// `stratum app cleanup <installation> [--yes]`: finishes a withdrawn
    /// installation's ACL cleanup. Asks first. Signed.
    ///
    /// For each container the node lists as pending, the client reads its
    /// ACL, removes only the installation's authorisation, writes the ACL
    /// back with `If-Match` (starting again on 412), reads it back and
    /// compares the parsed statements, and reports that container cleaned
    /// at once, so an interruption keeps what was done. An ACL that no
    /// longer holds the authorisation counts as clean. Nothing is kept on
    /// this machine: the pending list is the node's.
    ///
    /// # Errors
    ///
    /// [`CliError::NotConfirmed`]; [`CliError::CleanupPending`] when a
    /// container could not be cleaned, or [`CliError::AclNotEvaluated`]
    /// when its ACL holds a statement the client does not evaluate; key,
    /// transport, protocol and server errors.
    pub fn app_cleanup(
        &self,
        target: &GateTarget,
        installation: &InstallationId,
        confirmation: Confirmation,
    ) -> Result<u8, CliError> {
        self.with_tenant(target, |tenant| {
            let (view, _raw) = tenant.installation(installation)?;
            if view.grant != GrantState::Withdrawn || view.cleanup_pending.is_empty() {
                self.output().json(&json!({
                    "installation": installation,
                    "grant": view.grant,
                    "cleanup_pending": [],
                }))?;
                self.output().line(&format!(
                    "installation {installation}: no ACL cleanup is pending (grant {})",
                    view.grant
                ))?;
                return Ok(exit::OK);
            }
            let question = format!(
                "remove installation {installation}'s authorisation from {} container ACL(s)?",
                view.cleanup_pending.len()
            );
            if !self.confirmed(&question, confirmation)? {
                return Err(CliError::NotConfirmed);
            }
            let report = tenant.cleanup(&view, &view.cleanup_pending)?;
            self.output().json(&json!({
                "installation": installation,
                "cleanup": report.json(),
            }))?;
            report.finish(installation)
        })
    }

    /// `stratum app resume <installation> [--yes]`: after a restore, enables
    /// the installation's key again by removing its `restore` reason. Asks
    /// first. Signed. Only an `active` installation of an `active` member
    /// can be resumed.
    ///
    /// # Errors
    ///
    /// [`CliError::NotConfirmed`], and key, transport, protocol and server
    /// errors (`conflict` for an installation that cannot be resumed).
    pub fn app_resume(
        &self,
        target: &GateTarget,
        installation: &InstallationId,
        operation_id_arg: Option<&str>,
        confirmation: Confirmation,
    ) -> Result<u8, CliError> {
        let operation = operation_id(operation_id_arg)?;
        self.with_tenant(target, |tenant| {
            if !self.confirmed(
                &format!("enable installation {installation}'s key again after the restore?"),
                confirmation,
            )? {
                return Err(CliError::NotConfirmed);
            }
            tenant.note_operation(&operation, "")?;
            let body = to_body(&InstallationActionRequest {
                operation_id: operation.clone(),
            })?;
            let (answer, _raw): (ResumeInstallationResponse, Json) =
                tenant.post(&format!("{INSTALLATIONS}/{installation}/resume"), &body)?;
            self.output().json(&json!({
                "operation_id": operation.as_str(),
                "installation": installation,
                "keys": answer.keys,
            }))?;
            self.output()
                .line(&format!("installation {installation}: key {}", answer.keys))?;
            Ok(exit::OK)
        })
    }

    /// Runs `command` as the key's tenant, then shows every withdrawn grant
    /// whose cleanup is not yet reported, whatever the command's outcome
    /// (contract "Grant": every `stratum app` command shows it).
    fn with_tenant(
        &self,
        target: &GateTarget,
        command: impl FnOnce(&Tenant<'_>) -> Result<u8, CliError>,
    ) -> Result<u8, CliError> {
        let key = self.key()?;
        let tenant = Tenant {
            session: self,
            gate: GateClient::new(target.clone()).with_busy_retries(*self.output()),
            owner: key.public(),
            key,
        };
        let result = command(&tenant);
        tenant.show_pending_cleanup();
        result
    }
}

impl Tenant<'_> {
    /// `GET path` on a tenant route, parsed as `T`.
    fn get<T: DeserializeOwned>(&self, path: &str) -> Result<(T, Json), CliError> {
        self.gate
            .fetch(
                &Request::new("GET", path, JSON),
                Some(&self.key),
                MAX_RESPONSE_BYTES,
            )?
            .into_json(Route::Admission)
    }

    /// `POST path` with a JSON body on a tenant route, parsed as `T`.
    fn post<T: DeserializeOwned>(&self, path: &str, body: &[u8]) -> Result<(T, Json), CliError> {
        self.gate
            .fetch(
                &Request::new("POST", path, JSON).with_body(body, JSON),
                Some(&self.key),
                MAX_RESPONSE_BYTES,
            )?
            .into_json(Route::Admission)
    }

    /// Notes the operation ID before a `POST`, for a retry.
    fn note_operation(
        &self,
        operation: &stratum_node_core::OperationId,
        flags: &str,
    ) -> Result<(), CliError> {
        self.session.output().note(&format!(
            "operation id: {operation} (to retry after a lost response, pass --operation-id \
             {operation}{flags}: the retry must send the same request)"
        ))
    }

    /// `GET /api/v1/installations/<id>`, checked to name `installation` and
    /// this owner.
    fn installation(
        &self,
        installation: &InstallationId,
    ) -> Result<(InstallationView, Json), CliError> {
        let (view, raw): (InstallationView, Json) =
            self.get(&format!("{INSTALLATIONS}/{installation}"))?;
        if view.installation != *installation || view.owner != self.owner {
            return Err(CliError::Refused(format!(
                "asked for installation {installation} of {}, the node answered with {} of {}",
                self.owner, view.installation, view.owner
            )));
        }
        Ok((view, raw))
    }

    /// Notes every withdrawn grant whose cleanup is not reported. Any
    /// failure is ignored: while the owner is suspended the list is
    /// refused, and the contract does not show it then.
    fn show_pending_cleanup(&self) {
        let Ok((list, _raw)) = self.get::<InstallationList>(INSTALLATIONS) else {
            return;
        };
        for view in &list.installations {
            if view.owner != self.owner
                || view.grant != GrantState::Withdrawn
                || view.cleanup_pending.is_empty()
            {
                continue;
            }
            let paths: Vec<&str> = view
                .cleanup_pending
                .iter()
                .map(ContainerPath::as_str)
                .collect();
            // Nowhere useful to report a failed note.
            let _noted = self.session.output().note(&format!(
                "installation {} was withdrawn and its ACL cleanup is pending for {}: run \
                 `stratum app cleanup {}`",
                view.installation,
                paths.join(", "),
                view.installation
            ));
        }
    }

    /// Reads an ACL: `None` for 404, else its bytes and entity tag.
    fn read_acl(&self, acl: &PodPath) -> Result<Option<(Vec<u8>, String)>, CliError> {
        let response = self.gate.fetch(
            &Request::new("GET", acl.as_str(), ANY),
            Some(&self.key),
            MAX_ACL_BYTES,
        )?;
        if response.head.status == 404 {
            return Ok(None);
        }
        if !response.head.is_success() {
            return Err(response.into_error(Route::Pod));
        }
        let Some(etag) = response.head.etag.clone() else {
            return Err(CliError::Protocol(format!(
                "{acl} was read without an entity tag, so it cannot be written conditionally"
            )));
        };
        Ok(Some((response.body, etag)))
    }

    /// Writes `body` to `acl` under `precondition`.
    fn put_acl(
        &self,
        acl: &PodPath,
        body: &[u8],
        precondition: Precondition<'_>,
    ) -> Result<Put, CliError> {
        let request = Request::new("PUT", acl.as_str(), ANY)
            .with_body(body, TURTLE)
            .with_precondition(precondition);
        let response = self
            .gate
            .fetch(&request, Some(&self.key), MAX_RESPONSE_BYTES)?;
        if response.head.status == 412 {
            return Ok(Put::Lost);
        }
        if !response.head.is_success() {
            return Err(response.into_error(Route::Pod));
        }
        Ok(Put::Done)
    }

    /// Parses an ACL read from `acl`.
    fn parse(&self, acl: &PodPath, bytes: &[u8]) -> Result<AclDocument, CliError> {
        let origin = self.gate.target().origin();
        acl::parse(&origin.url(acl.as_str()), acl, &origin.as_str(), bytes)
    }

    /// Reads what governs `container`, nearest first: its own ACL, then each
    /// ancestor's. An ancestor ACL this install has planned but not written
    /// is taken from `planned`. Only a 404 moves up a level; any other
    /// failure is an error, never a miss.
    fn read_governing(
        &self,
        container: &PodPath,
        planned: &HashMap<PodPath, AclDocument>,
    ) -> Result<(Governing, Fingerprint, Option<Vec<u8>>), CliError> {
        for candidate in acl::governing_candidates(container) {
            let Some(acl) = candidate.acl_path() else {
                continue;
            };
            let own = candidate == *container;
            if !own {
                if let Some(document) = planned.get(&acl) {
                    return Ok((
                        Governing::Inherited {
                            acl: acl.clone(),
                            document: document.clone(),
                        },
                        Fingerprint::Planned(acl),
                        None,
                    ));
                }
            }
            let Some((bytes, etag)) = self.read_acl(&acl)? else {
                continue;
            };
            let document = self.parse(&acl, &bytes)?;
            return Ok(if own {
                (
                    Governing::Own(document),
                    Fingerprint::Own(etag),
                    Some(bytes),
                )
            } else {
                (
                    Governing::Inherited {
                        acl: acl.clone(),
                        document,
                    },
                    Fingerprint::Inherited(acl, etag),
                    None,
                )
            });
        }
        Ok((Governing::Nothing, Fingerprint::Nothing, None))
    }

    /// Plans one container's ACL from what governs it now.
    fn plan(
        &self,
        container: &PodPath,
        app: &DidNostr,
        offered_text: &str,
        planned: &HashMap<PodPath, AclDocument>,
    ) -> Result<Planned, CliError> {
        let acl = container
            .acl_path()
            .ok_or_else(|| CliError::Protocol(format!("{container} has no ACL path")))?;
        let url = self.gate.target().origin().url(acl.as_str());
        let offered = self
            .parse(&acl, offered_text.as_bytes())
            .map_err(|_| {
                CliError::Protocol(format!("the offered rule for {container} does not parse"))
            })?
            .authorisations;
        let [offered] = <[Authorisation; 1]>::try_from(offered).map_err(|_| {
            CliError::Protocol(format!(
                "the offered rule for {container} is not exactly one authorisation"
            ))
        })?;
        let (governing, fingerprint, previous) = self.read_governing(container, planned)?;
        let document = acl::materialise(&acl::Materialise {
            owner: &self.owner,
            app,
            container,
            url: &url,
            governing: &governing,
            offered: &offered,
        })?;
        let text = acl::serialise(&document)?;
        // The text must say exactly what was built.
        let reparsed = self.parse(&acl, text.as_bytes())?;
        if !reparsed.same_statements(&document) {
            return Err(CliError::Local(format!(
                "the ACL built for {container} does not parse back to its own statements"
            )));
        }
        Ok(Planned {
            container: container.clone(),
            acl,
            fingerprint,
            previous,
            document,
            text,
        })
    }

    /// The preview lines of one container.
    fn describe_plan(planned: &Planned) -> Vec<String> {
        let governed = match &planned.fingerprint {
            Fingerprint::Own(_) => "governed now by its own ACL, which is kept".to_owned(),
            Fingerprint::Inherited(acl, _) | Fingerprint::Planned(acl) => format!(
                "governed now by {acl}: its rules that reach this container by acl:default are \
                 copied into a new ACL, so every principal keeps exactly its access"
            ),
            Fingerprint::Nothing => "governed now by no ACL".to_owned(),
        };
        let old = planned
            .previous
            .as_deref()
            .map(String::from_utf8_lossy)
            .unwrap_or_default();
        let mut lines = vec![
            format!("container {} (ACL {})", planned.container, planned.acl),
            format!("  {governed}"),
        ];
        lines.extend(
            acl::diff(&old, &planned.text)
                .into_iter()
                .map(|line| format!("  {}", sanitize(&line))),
        );
        lines
    }

    /// `app install`, after the local checks.
    #[expect(
        clippy::too_many_lines,
        reason = "the install sequence reads best as one ordered procedure"
    )]
    fn install(
        &self,
        options: &InstallOptions,
        operation: &stratum_node_core::OperationId,
    ) -> Result<u8, CliError> {
        let output = self.session.output();
        let (catalogue, _raw): (Catalogue, Json) = self.get(CATALOGUE)?;
        let Some(entry) = catalogue
            .applications
            .into_iter()
            .find(|entry| entry.application == options.application)
        else {
            return Err(CliError::Usage(format!(
                "application {} is not in this node's catalogue: only approved applications can \
                 be installed; `stratum app catalogue` lists them",
                options.application
            )));
        };
        let manifest = &entry.manifest;
        if options.workspace > manifest.workspace {
            return Err(CliError::Usage(format!(
                "--workspace {} is more than application {} allows ({})",
                options.workspace, options.application, manifest.workspace
            )));
        }
        let schedule_flag = if options.schedule_secs == 0 {
            String::new()
        } else {
            format!(" --schedule {}", options.schedule_secs)
        };
        let workspace_flag = if options.workspace == WorkspaceMode::None {
            String::new()
        } else {
            format!(" --workspace {}", options.workspace)
        };
        self.note_operation(operation, &format!("{schedule_flag}{workspace_flag}"))?;
        let body = to_body(&CreateInstallationRequest {
            operation_id: operation.clone(),
            application: options.application,
            schedule_secs: options.schedule_secs,
            workspace: options.workspace,
        })?;
        let (created, _raw): (CreateInstallationResponse, Json) =
            self.post(INSTALLATIONS, &body)?;
        let installation = created.installation;
        if created.state != InstallationState::PendingConsent {
            return Err(CliError::Refused(format!(
                "the node reports installation {installation} as {}, not pending_consent",
                created.state
            )));
        }
        let app = created.app_did;
        if app == self.owner {
            return Err(CliError::Refused(
                "the node offered your own key as the application key".to_owned(),
            ));
        }
        let expected = render_offered(&app, &self.owner, &manifest.containers);
        if created.grant != expected {
            return Err(CliError::Refused(format!(
                "the grant the node offered for installation {installation} is not the one the \
                 manifest renders for key {app} (offered sha256 {}, rendered {})",
                created.grant.sha256, expected.sha256
            )));
        }
        let grant: OfferedGrant = created.grant;

        // Plan every container before asking, in manifest order; a granted
        // container nested in another sees that one's planned ACL.
        let mut planned_documents: HashMap<PodPath, AclDocument> = HashMap::new();
        let mut plans = Vec::with_capacity(grant.containers.len());
        for offered in &grant.containers {
            let container = offered.path.under(&self.owner);
            let plan = self.plan(&container, &app, &offered.turtle, &planned_documents)?;
            planned_documents.insert(plan.acl.clone(), plan.document.clone());
            plans.push(plan);
        }

        let mut preview = vec![
            format!("installation: {installation} (pending consent)"),
            format!("owner: {}", self.owner),
            format!(
                "application: {} {} (version {})",
                entry.application,
                sanitize(&manifest.name),
                sanitize(&manifest.version)
            ),
            format!("image: {}", manifest.image_id),
            format!("application key: {app}"),
            format!(
                "schedule: {}",
                if options.schedule_secs == 0 {
                    "manual runs only".to_owned()
                } else {
                    format!("every {} s", options.schedule_secs)
                }
            ),
            format!("workspace: {}", options.workspace),
            format!("grant sha256: {}", grant.sha256),
        ];
        for plan in &plans {
            preview.extend(Self::describe_plan(plan));
        }
        preview.push(OPERATOR_STATEMENT.to_owned());
        for line in &preview {
            output.line(line)?;
        }
        let mut report = json!({
            "operation_id": operation.as_str(),
            "installation": installation,
            "application": entry.application,
            "name": manifest.name,
            "version": manifest.version,
            "image_id": manifest.image_id,
            "owner": self.owner,
            "app_did": app,
            "grant_sha256": grant.sha256,
            "statement": OPERATOR_STATEMENT,
            "containers": plans.iter().map(|plan| json!({
                "path": plan.container,
                "acl": plan.acl,
                "governed_by": match &plan.fingerprint {
                    Fingerprint::Own(_) => Json::from(plan.acl.as_str()),
                    Fingerprint::Inherited(acl, _) | Fingerprint::Planned(acl) => Json::from(acl.as_str()),
                    Fingerprint::Nothing => Json::Null,
                },
                "acl_text": plan.text,
                "diff": acl::diff(
                    &plan.previous.as_deref().map(String::from_utf8_lossy).unwrap_or_default(),
                    &plan.text,
                ),
            })).collect::<Vec<_>>(),
            "consented": false,
            "state": InstallationState::PendingConsent,
        });
        let question = format!(
            "write these ACLs and consent to installation {installation} of {}?",
            sanitize(&manifest.name)
        );
        if !self.session.confirmed(&question, options.confirmation)? {
            output.json(&report)?;
            output.note(&format!(
                "nothing was written; installation {installation} stays pending_consent. Withdraw \
                 it with `stratum app withdraw {installation}`, or continue it by running install \
                 again with --operation-id {operation}{schedule_flag}{workspace_flag}"
            ))?;
            return Err(CliError::NotConfirmed);
        }

        let mut written: Vec<Written> = Vec::new();
        for (index, approved) in plans.iter().enumerate() {
            let offered_text = &grant.containers[index].turtle;
            if let Err(err) = self.write_container(
                &installation,
                &app,
                approved,
                offered_text,
                options,
                &mut written,
            ) {
                let left = self.remove_written(&written);
                return Err(with_removal(err, &left));
            }
        }

        let body = to_body(&ConsentRequest {
            operation_id: operation_id(None)?,
            grant_sha256: grant.sha256,
            read_back: true,
        })?;
        let consent: Result<(ConsentResponse, Json), CliError> =
            self.post(&format!("{INSTALLATIONS}/{installation}/consent"), &body);
        let consent = match consent {
            Ok((answer, _raw)) => answer,
            Err(err) if is_definite_refusal(&err) => {
                let left = self.remove_written(&written);
                return Err(with_removal(
                    CliError::ConsentRefused(format!(
                        "the node refused consent to installation {installation}: {err}"
                    )),
                    &left,
                ));
            }
            // A lost answer, or a 5xx from behind the gate: the consent may
            // have been recorded, so the ACLs stay, and the person is told
            // how to find out.
            Err(err) => {
                output.note(&format!(
                    "the consent's outcome is unknown; the ACLs were left in place. `stratum app \
                     show {installation}` reports whether it is active, and `stratum app \
                     withdraw {installation}` removes them if not"
                ))?;
                return Err(err);
            }
        };
        if consent.state != InstallationState::Active {
            return Err(CliError::Refused(format!(
                "the node reports installation {installation} as {} after consent",
                consent.state
            )));
        }
        report["consented"] = Json::Bool(true);
        report["state"] = json!(consent.state);
        report["workspace"] = json!(consent.workspace);
        output.json(&report)?;
        output.line(&format!(
            "installation {installation}: active; {} container ACL(s) written and read back",
            written.len()
        ))?;
        Ok(exit::OK)
    }

    /// Writes one container's ACL: the reread, the conditional write and
    /// the read-back, starting again from the read when the governing ACL
    /// changed or the write lost a race.
    fn write_container(
        &self,
        installation: &InstallationId,
        app: &DidNostr,
        approved: &Planned,
        offered_text: &str,
        options: &InstallOptions,
        written: &mut Vec<Written>,
    ) -> Result<(), CliError> {
        let output = self.session.output();
        let mut approved_text = approved.text.clone();
        let none = HashMap::new();
        for attempt in 1..=MAX_ACL_ATTEMPTS {
            let plan = self.plan(&approved.container, app, offered_text, &none)?;
            if plan.text != approved_text {
                output.note(&format!(
                    "the ACL governing {} changed since the preview; the new ACL is:",
                    plan.container
                ))?;
                for line in Self::describe_plan(&plan) {
                    output.note(&line)?;
                }
                if !self.session.confirmed(
                    &format!("write this ACL for {}?", plan.container),
                    options.confirmation,
                )? {
                    return Err(CliError::NotConfirmed);
                }
                approved_text.clone_from(&plan.text);
            }
            let (view, _raw) = self.installation(installation)?;
            if view.state != InstallationState::PendingConsent {
                return Err(CliError::ConsentRefused(format!(
                    "installation {installation} is {} and no longer pending_consent, so no more \
                     of its grant is written",
                    view.state
                )));
            }
            // Reread immediately before the write.
            let (_governing, fingerprint, _previous) =
                self.read_governing(&plan.container, &none)?;
            if fingerprint != plan.fingerprint {
                output.note(&format!(
                    "the ACL governing {} changed while it was being written; reading it again \
                     (attempt {attempt} of {MAX_ACL_ATTEMPTS})",
                    plan.container
                ))?;
                continue;
            }
            let precondition = match &plan.fingerprint {
                Fingerprint::Own(etag) => Precondition::IfMatch(etag),
                _ => Precondition::CreateOnly,
            };
            match self.put_acl(&plan.acl, plan.text.as_bytes(), precondition)? {
                Put::Lost => {
                    output.note(&format!(
                        "{} changed before the write landed; reading it again (attempt {attempt} \
                         of {MAX_ACL_ATTEMPTS})",
                        plan.acl
                    ))?;
                    continue;
                }
                Put::Done => {}
            }
            let Some((bytes, etag)) = self.read_acl(&plan.acl)? else {
                return Err(CliError::ReadBackMismatch(format!(
                    "{}: its ACL {} was absent when read back; consent was not sent",
                    plan.container, plan.acl
                )));
            };
            let back = self.parse(&plan.acl, &bytes).map_err(|err| {
                CliError::ReadBackMismatch(format!(
                    "{}: its ACL did not read back as written ({err}); consent was not sent",
                    plan.container
                ))
            })?;
            if !back.same_statements(&plan.document) {
                return Err(CliError::ReadBackMismatch(format!(
                    "{}: its ACL {} did not read back with the statements written and was left \
                     in place; consent was not sent",
                    plan.container, plan.acl
                )));
            }
            acl::check_no_app_control(&back, app, &plan.container)?;
            // Record the rollback ETag only after confirming the read-back
            // matches what we wrote, so rollback can never delete or overwrite
            // a concurrent editor's ACL.
            written.push(Written {
                acl: plan.acl.clone(),
                previous: plan.previous.clone(),
                etag,
            });
            output.note(&format!("{}: ACL written and read back", plan.container))?;
            return Ok(());
        }
        Err(CliError::Server {
            status: 412,
            code: "precondition_failed".to_owned(),
            message: format!(
                "the ACL governing {} changed {MAX_ACL_ATTEMPTS} times while it was being \
                 written; nothing more was written",
                approved.container
            ),
            details: Vec::new(),
        })
    }

    /// Removes what this run wrote, newest first: an ACL the client created
    /// is deleted, one it replaced gets its earlier bytes back, each only if
    /// it is still what the client read back. Returns what could not be
    /// removed.
    fn remove_written(&self, written: &[Written]) -> Vec<String> {
        let mut left = Vec::new();
        for entry in written.iter().rev() {
            let precondition = Precondition::IfMatch(&entry.etag);
            let result = match &entry.previous {
                None => self
                    .gate
                    .fetch(
                        &Request::new("DELETE", entry.acl.as_str(), ANY)
                            .with_precondition(precondition),
                        Some(&self.key),
                        MAX_RESPONSE_BYTES,
                    )
                    .map(|response| response.head.status),
                Some(previous) => self
                    .gate
                    .fetch(
                        &Request::new("PUT", entry.acl.as_str(), ANY)
                            .with_body(previous, TURTLE)
                            .with_precondition(precondition),
                        Some(&self.key),
                        MAX_RESPONSE_BYTES,
                    )
                    .map(|response| response.head.status),
            };
            match result {
                Ok(status) if (200..300).contains(&status) => {}
                Ok(status) => left.push(format!("{} (HTTP {status})", entry.acl)),
                Err(err) => left.push(format!("{} ({err})", entry.acl)),
            }
        }
        left
    }

    /// Cleans every container in `pending` for the withdrawn installation
    /// `view`, reporting each to the node as soon as it is clean.
    fn cleanup(
        &self,
        view: &InstallationView,
        pending: &[ContainerPath],
    ) -> Result<CleanupReport, CliError> {
        let output = self.session.output();
        let installation = view.installation;
        let mut report = CleanupReport::default();
        for path in pending {
            let outcome = match &view.app_did {
                // No key was ever recorded, so no grant naming it was
                // written by this or any client.
                None => Ok(()),
                Some(app) => self.clean_container(&path.under(&self.owner), app),
            };
            match outcome {
                Ok(()) => {
                    let body = to_body(&CleanupRequest {
                        operation_id: operation_id(None)?,
                        containers: vec![path.clone()],
                        read_back: true,
                    })?;
                    let (answer, _raw): (CleanupResponse, Json) =
                        self.post(&format!("{INSTALLATIONS}/{installation}/cleanup"), &body)?;
                    output.note(&format!("{path}: cleaned, read back and reported"))?;
                    report.cleaned.push(path.clone());
                    report.grant = Some(answer.grant);
                    report.pending = answer.cleanup_pending;
                }
                Err(err) => {
                    output.note(&format!("{path}: not cleaned: {err}"))?;
                    report.not_evaluated |= matches!(err, CliError::AclNotEvaluated(_));
                    report.failed.push((path.clone(), err.to_string()));
                }
            }
        }
        if report.grant.is_none() {
            report.pending = pending.to_vec();
            report.grant = Some(view.grant);
        }
        Ok(report)
    }

    /// Removes the installation's authorisation from one container's ACL,
    /// with `If-Match`, then reads it back.
    fn clean_container(&self, container: &PodPath, app: &DidNostr) -> Result<(), CliError> {
        let output = self.session.output();
        let acl = container
            .acl_path()
            .ok_or_else(|| CliError::Protocol(format!("{container} has no ACL path")))?;
        for attempt in 1..=MAX_ACL_ATTEMPTS {
            let Some((bytes, etag)) = self.read_acl(&acl)? else {
                return Ok(());
            };
            let document = self.parse(&acl, &bytes)?;
            let others = acl::other_mentions(&document, app);
            if others > 0 {
                output.note(&format!(
                    "{acl}: {others} other authorisation(s) name the application key; they were \
                     not written by this installation and are left as they are"
                ))?;
            }
            let Some(cleaned) = acl::remove_installation(&document, app) else {
                return Ok(());
            };
            let text = acl::serialise(&cleaned)?;
            match self.put_acl(&acl, text.as_bytes(), Precondition::IfMatch(&etag))? {
                Put::Lost => {
                    output.note(&format!(
                        "{acl} changed before the edit landed; reading it again (attempt \
                         {attempt} of {MAX_ACL_ATTEMPTS})"
                    ))?;
                    continue;
                }
                Put::Done => {}
            }
            let Some((back, _etag)) = self.read_acl(&acl)? else {
                return Err(CliError::Protocol(format!(
                    "{acl} was absent when read back"
                )));
            };
            if !self.parse(&acl, &back)?.same_statements(&cleaned) {
                return Err(CliError::Protocol(format!(
                    "{acl} did not read back with the statements written"
                )));
            }
            return Ok(());
        }
        Err(CliError::Protocol(format!(
            "{acl} changed {MAX_ACL_ATTEMPTS} times while it was being edited"
        )))
    }
}

/// What a cleanup did.
#[derive(Debug, Default)]
struct CleanupReport {
    cleaned: Vec<ContainerPath>,
    failed: Vec<(ContainerPath, String)>,
    pending: Vec<ContainerPath>,
    grant: Option<GrantState>,
    not_evaluated: bool,
}

impl CleanupReport {
    /// The report as JSON.
    fn json(&self) -> Json {
        json!({
            "cleaned": self.cleaned,
            "failed": self.failed.iter().map(|(path, why)| json!({"path": path, "error": why})).collect::<Vec<_>>(),
            "cleanup_pending": self.pending,
            "grant": self.grant,
        })
    }

    /// Prints the outcome and returns the exit: success when nothing is
    /// pending.
    fn finish(&self, installation: &InstallationId) -> Result<u8, CliError> {
        if self.pending.is_empty() && self.failed.is_empty() {
            return Ok(exit::OK);
        }
        let paths: Vec<&str> = self
            .pending
            .iter()
            .map(ContainerPath::as_str)
            .chain(self.failed.iter().map(|(path, _)| path.as_str()))
            .collect::<std::collections::BTreeSet<_>>()
            .into_iter()
            .collect();
        let message = format!(
            "installation {installation}: ACL cleanup is still pending for {}",
            paths.join(", ")
        );
        if self.not_evaluated {
            return Err(CliError::AclNotEvaluated(message));
        }
        Err(CliError::CleanupPending(message))
    }
}

/// Whether a failed consent was certainly not recorded: a 4xx refusal, or
/// the gate's 503 `gate_unavailable`, which forwarded nothing. A transport
/// failure or any other 5xx (`bad_gateway`, `gateway_timeout`, `internal`)
/// leaves the outcome unknown: the node may have committed the consent
/// before the answer was lost.
fn is_definite_refusal(err: &CliError) -> bool {
    match err {
        CliError::Server { status, code, .. } => {
            (400..500).contains(status) || (*status == 503 && code == "gate_unavailable")
        }
        _ => false,
    }
}

/// Adds what could not be removed to an install failure.
fn with_removal(err: CliError, left: &[String]) -> CliError {
    if left.is_empty() {
        return err;
    }
    let tail = format!("; NOT removed: {}", left.join(", "));
    match err {
        CliError::ReadBackMismatch(message) => {
            CliError::ReadBackMismatch(format!("{message}{tail}"))
        }
        CliError::ConsentRefused(message) => CliError::ConsentRefused(format!("{message}{tail}")),
        CliError::AclNotEvaluated(message) => CliError::AclNotEvaluated(format!("{message}{tail}")),
        CliError::Refused(message) => CliError::Refused(format!("{message}{tail}")),
        other => CliError::ConsentRefused(format!("{other}{tail}")),
    }
}

/// The human lines of one catalogue entry.
fn describe_entry(entry: &CatalogueEntry) -> Vec<String> {
    let manifest = &entry.manifest;
    let mut lines = vec![format!(
        "{}  {} {}  image {}  workspace up to {}",
        entry.application,
        sanitize(&manifest.name),
        sanitize(&manifest.version),
        manifest.image_id,
        manifest.workspace
    )];
    for container in &manifest.containers {
        let modes: Vec<&str> = container.modes.iter().map(|m| m.as_str()).collect();
        let operations: Vec<&str> = container.operations.iter().map(|o| o.as_str()).collect();
        lines.push(format!(
            "  {}  {}  ({})",
            container.path,
            modes.join(", "),
            operations.join(", ")
        ));
    }
    lines
}

/// One line per installation for `app list` and `stratum installations`.
pub(crate) fn summary_line(view: &InstallationView) -> String {
    let mut line = format!(
        "{}  {}  application {}  grant {}  jobs {} (pending {}, running {}, succeeded {}, failed {})",
        view.installation,
        view.state,
        view.application,
        view.grant,
        view.jobs.total(),
        view.jobs.pending,
        view.jobs.running,
        view.jobs.succeeded,
        view.jobs.failed,
    );
    if !view.key_reasons.is_empty() {
        let reasons: Vec<&str> = view.key_reasons.iter().map(|r| r.as_str()).collect();
        let _ = write!(line, "  key disabled: {}", reasons.join(", "));
    }
    if view.grant == GrantState::Withdrawn && !view.cleanup_pending.is_empty() {
        let paths: Vec<&str> = view
            .cleanup_pending
            .iter()
            .map(ContainerPath::as_str)
            .collect();
        let _ = write!(line, "  ACL cleanup pending: {}", paths.join(", "));
    }
    line
}

/// The human lines of `app show`.
fn describe_view(view: &InstallationView) -> Vec<String> {
    let time = |t: Option<stratum_node_core::UnixTime>| {
        t.map_or_else(|| "-".to_owned(), |t| t.to_string())
    };
    let mut lines = vec![
        format!("installation: {}", view.installation),
        format!("state: {}", view.state),
        format!("application: {}", view.application),
        format!("owner: {}", view.owner),
        format!("generation: {}", view.generation),
        format!(
            "application key: {}",
            view.app_did
                .map_or_else(|| "-".to_owned(), |d| d.to_string())
        ),
        format!(
            "schedule: {}",
            if view.schedule_secs == 0 {
                "manual runs only".to_owned()
            } else {
                format!("every {} s", view.schedule_secs)
            }
        ),
        format!("workspace: {}", view.workspace),
        format!("created at: {}", view.created_at),
        format!("activated at: {}", time(view.activated_at)),
        format!("withdrawn at: {}", time(view.withdrawn_at)),
        format!(
            "key disabled by: {}",
            if view.key_reasons.is_empty() {
                "-".to_owned()
            } else {
                view.key_reasons
                    .iter()
                    .map(|r| r.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            }
        ),
        format!(
            "grant: {} (as your client reported it to the node)",
            view.grant
        ),
    ];
    if view.grant == GrantState::Withdrawn && !view.cleanup_pending.is_empty() {
        let paths: Vec<&str> = view
            .cleanup_pending
            .iter()
            .map(ContainerPath::as_str)
            .collect();
        lines.push(format!(
            "ACL cleanup pending: {} (run `stratum app cleanup {}`)",
            paths.join(", "),
            view.installation
        ));
    }
    if let Some(parts) = &view.enforcement {
        lines.push(format!(
            "enforcement: authorisation {}, keys {}, work {}",
            parts.authorisation, parts.keys, parts.work
        ));
    }
    lines.push(format!(
        "jobs: {} (pending {}, running {}, succeeded {}, failed {}, cancelled {}, conflict {}, skipped {})",
        view.jobs.total(),
        view.jobs.pending,
        view.jobs.running,
        view.jobs.succeeded,
        view.jobs.failed,
        view.jobs.cancelled,
        view.jobs.conflict,
        view.jobs.skipped
    ));
    lines
}