openlatch-client 0.3.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
//! The single diagnostic model shared by `init`, `doctor`, `status` and the
//! per-subsystem status commands.
//!
//! Before this module every command answered "is OpenLatch healthy?" its own
//! way, and the answers disagreed. `doctor` reported a disabled model boundary
//! as a **pass** while `status` printed it as `disabled` and `boundary status`
//! called the same state `down` and suggested a command that could not fix it.
//! One model, one renderer, one exit code.
//!
//! ## The contract
//!
//! - **P1** Green means *enabled AND proven working*. Nothing else is green.
//! - **P2** Deliberately disabled is a warning, never silence.
//! - **P3** Enabled but not working is a failure, even when the failure is
//!   tolerated at runtime.
//! - **P6** The same [`Section`]s are always reported, in the same order, even
//!   when empty — "I don't know" is a state, not an omission.
//! - **P7** Everything in the human rendering exists in the JSON rendering.
//!
//! ## Anti-cascade
//!
//! A failure does not propagate. When the daemon is dead, the sections that
//! depend on it report [`State::Unknown`] — a *warning* naming the blocker —
//! rather than each inventing a failure of its own. One outage, one cross.

use crate::cli::color;
use crate::cli::output::{OutputConfig, OutputFormat};

/// Display width of the field [`State::mark`] always occupies, separator
/// included.
const MARK_WIDTH: usize = 5;

/// Width of the section-title cell in the grouped rendering. The longest title
/// is `Environment` / `Persistence`, both eleven.
const TITLE_WIDTH: usize = 11;

/// Indent for a check's continuation lines — detail, source, remedy — in the
/// single-section view.
///
/// Two spaces of indent plus [`MARK_WIDTH`], so a continuation starts exactly
/// under the headline it belongs to rather than a space further in.
const CONTINUATION: &str = "       ";

/// Everything requested is running, but at least one subsystem is switched off
/// or not at full capability.
///
/// **Why 7 and not 2.** The exit-code table in `.claude/rules/error-handling.md`
/// is a public contract, and it already spends 2 on usage errors — which clap
/// produces itself for a mistyped flag, before any of our code runs. Reusing it
/// would leave a script unable to tell `openlatch doctor --bogus` from
/// `openlatch doctor` on a host with the model boundary switched off. 3
/// (not found), 4 (permission), 5 (conflict — reserved for `OL-1501`, which
/// `systemd`'s `RestartPreventExitStatus=5` keys off) and 6 (`update`'s
/// daemon-unreachable) are likewise taken. 7 is the first free number.
///
/// It is deliberately NOT 0: `openlatch doctor && deploy` succeeding on a host
/// where nothing is captured or enforced is the failure mode this whole
/// contract exists to close.
pub const EXIT_DEGRADED: i32 = 7;

/// Process-level verdict recorded by a diagnostic rendering, read by `main`
/// when the command itself returned `Ok`.
///
/// Exists because a command can succeed at *running* and still need to report
/// that the machine is degraded: `doctor` finding a disabled boundary is not an
/// `OlError` — printing "Error:" in front of it would be a lie — but it must
/// not exit 0 either, or `openlatch doctor && deploy` ships with enforcement
/// off. `update` solves the same problem by calling `process::exit` directly,
/// which silently skips the `command_invoked` telemetry; this keeps the normal
/// return path intact.
mod verdict {
    use std::sync::atomic::{AtomicI32, Ordering};

    static PENDING: AtomicI32 = AtomicI32::new(0);

    /// Severity of an exit status, since the numbers do not order themselves:
    /// `1` (failure) outranks `7` (degraded), which outranks `0`.
    fn severity(code: i32) -> u8 {
        match code {
            0 => 0,
            super::EXIT_DEGRADED => 1,
            _ => 2,
        }
    }

    /// Record the exit status a successful command wants the process to carry.
    /// Worst wins, so a later benign rendering cannot clear an earlier failure.
    pub fn record(code: i32) {
        let mut current = PENDING.load(Ordering::SeqCst);
        while severity(code) > severity(current) {
            match PENDING.compare_exchange(current, code, Ordering::SeqCst, Ordering::SeqCst) {
                Ok(_) => return,
                Err(observed) => current = observed,
            }
        }
    }

    /// The recorded status, or 0 when nothing was recorded.
    pub fn pending() -> i32 {
        PENDING.load(Ordering::SeqCst)
    }

    /// Reset — tests only; the process runs one command.
    #[cfg(test)]
    pub fn reset() {
        PENDING.store(0, Ordering::SeqCst);
    }
}

#[cfg(test)]
pub use verdict::reset as reset_exit_code;
pub use verdict::{pending as pending_exit_code, record as record_exit_code};

// ---------------------------------------------------------------------------
// Groups
// ---------------------------------------------------------------------------

/// The three questions a reader asks, in the order they ask them.
///
/// Eleven flat sections is a bad ratio — eleven headings for twenty lines of
/// content, and the marks scattered across as many columns. Grouping puts every
/// section on one scan column and lets the green ones collapse to a line, so
/// what is left on screen is mostly the things that need attention.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Group {
    /// Is it running, and will it keep running?
    Runtime,
    /// Is it seeing everything, and is it enforcing?
    Coverage,
    /// Is any of what it sees leaving this machine?
    Platform,
}

impl Group {
    pub const ALL: [Group; 3] = [Group::Runtime, Group::Coverage, Group::Platform];

    pub fn title(self) -> &'static str {
        match self {
            Group::Runtime => "Runtime",
            Group::Coverage => "Coverage",
            Group::Platform => "Platform",
        }
    }

    pub fn key(self) -> &'static str {
        match self {
            Group::Runtime => "runtime",
            Group::Coverage => "coverage",
            Group::Platform => "platform",
        }
    }
}

// ---------------------------------------------------------------------------
// Sections
// ---------------------------------------------------------------------------

/// A subsystem of the install, ordered from most fundamental to most
/// peripheral. A section whose upstream dependency failed reports
/// [`State::Unknown`] rather than a failure of its own.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Section {
    /// Agent detection, `~/.claude`, `~/.openlatch`, config readability, build.
    Environment,
    /// The daemon process: alive, bound, healthy, and serving the installed
    /// version.
    Daemon,
    /// `settings.json` entries, the staged hook binary, token and port match.
    Hooks,
    /// The model-boundary listener and the agent's `ANTHROPIC_BASE_URL`.
    Boundary,
    /// OS-native supervision (launchd / systemd-user / Task Scheduler).
    Persistence,
    /// How this host reaches the platform: direct, or through a proxy. Owns the
    /// first hop, so "cannot reach the proxy" and "cannot reach the platform"
    /// are two rows rather than one collapsed `Cloud` failure.
    Connection,
    /// Forwarding to the OpenLatch platform. Never [`State::Off`] — the
    /// forwarding is constitutive of the product and cannot be switched off.
    Cloud,
    /// Local policy bundle: present, fresh, enforcing.
    Policy,
    /// The configuration plane monitor.
    Inventory,
    /// Anonymous usage telemetry consent.
    Telemetry,
    /// Drift between the installed binary and the one being served.
    Update,
    /// HMAC key, tamper log, hook markers.
    Integrity,
}

impl Section {
    /// Every section, in reporting order. Rendering walks this, not the order
    /// checks happened to be pushed in.
    pub const ALL: [Section; 12] = [
        // Runtime
        Section::Environment,
        Section::Daemon,
        Section::Persistence,
        Section::Update,
        // Coverage
        Section::Hooks,
        Section::Boundary,
        Section::Policy,
        Section::Inventory,
        Section::Integrity,
        // Platform — Connection first: it is the hop Cloud travels over, so a
        // reader meets the route before the thing at the end of it.
        Section::Connection,
        Section::Cloud,
        Section::Telemetry,
    ];

    /// Which question this section answers.
    ///
    /// `Policy` sits in `Coverage` rather than `Platform` on purpose: the
    /// bundle arrives from the cloud, but the evaluation is local and
    /// authoritative — it is about what this host enforces, not about what
    /// leaves it. `Inventory` is local observation for the same reason, and
    /// `Update` is in `Runtime` because version drift answers "which binary is
    /// actually running".
    pub fn group(self) -> Group {
        match self {
            Section::Environment | Section::Daemon | Section::Persistence | Section::Update => {
                Group::Runtime
            }
            Section::Hooks
            | Section::Boundary
            | Section::Policy
            | Section::Inventory
            | Section::Integrity => Group::Coverage,
            Section::Connection | Section::Cloud | Section::Telemetry => Group::Platform,
        }
    }

    /// Every section in a group, in reading order.
    pub fn of_group(group: Group) -> impl Iterator<Item = Section> {
        Section::ALL.into_iter().filter(move |s| s.group() == group)
    }

    /// Human-facing section title.
    pub fn title(self) -> &'static str {
        match self {
            Section::Environment => "Environment",
            Section::Daemon => "Daemon",
            Section::Hooks => "Hooks",
            Section::Boundary => "Boundary",
            Section::Persistence => "Persistence",
            Section::Connection => "Connection",
            Section::Cloud => "Cloud",
            Section::Policy => "Policy",
            Section::Inventory => "Inventory",
            Section::Telemetry => "Telemetry",
            Section::Update => "Update",
            Section::Integrity => "Integrity",
        }
    }

    /// Stable machine key for the JSON rendering.
    pub fn key(self) -> &'static str {
        match self {
            Section::Environment => "environment",
            Section::Daemon => "daemon",
            Section::Hooks => "hooks",
            Section::Boundary => "boundary",
            Section::Persistence => "persistence",
            Section::Connection => "connection",
            Section::Cloud => "cloud",
            Section::Policy => "policy",
            Section::Inventory => "inventory",
            Section::Telemetry => "telemetry",
            Section::Update => "update",
            Section::Integrity => "integrity",
        }
    }
}

// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------

/// What one check found.
///
/// The mapping to marks and exit codes is normative — see [`State::mark`] and
/// [`Report::exit_code`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
    /// Enabled and proven working. The only green state.
    Ok,
    /// Deliberately switched off — config, flag, or an explicit user opt-out.
    /// A warning: the user is entitled to this state, and entitled to be
    /// reminded they are in it.
    Off,
    /// Enabled, working, losing nothing — but not at full capability.
    Degraded,
    /// Enabled, verification still in flight. Ask again shortly.
    Pending,
    /// Enabled and not working.
    Failed,
    /// Indeterminable because the named section failed. Warns, never fails —
    /// this is what keeps one outage from printing eight crosses.
    Unknown(Section),
    /// Absent from this build or irrelevant on this platform. Not a problem,
    /// and not a success either.
    NotApplicable,
}

impl State {
    /// Severity for "worst wins" aggregation. Not a public ordering: it exists
    /// only to fold a section's checks into one state.
    fn severity(self) -> u8 {
        match self {
            State::NotApplicable => 0,
            State::Ok => 1,
            State::Pending => 2,
            State::Off => 3,
            State::Degraded => 4,
            State::Unknown(_) => 5,
            State::Failed => 6,
        }
    }

    /// Stable machine key for the JSON rendering.
    pub fn key(self) -> &'static str {
        match self {
            State::Ok => "ok",
            State::Off => "off",
            State::Degraded => "degraded",
            State::Pending => "pending",
            State::Failed => "failed",
            State::Unknown(_) => "unknown",
            State::NotApplicable => "not_applicable",
        }
    }

    /// Does this state count as a failure for the exit code?
    pub fn is_failure(self) -> bool {
        self == State::Failed
    }

    /// Does this state count as a warning for the exit code?
    pub fn is_warning(self) -> bool {
        matches!(
            self,
            State::Off | State::Degraded | State::Pending | State::Unknown(_)
        )
    }

    /// Must this state carry a code and a remedy?
    ///
    /// Everything the operator is expected to act on must say what to do. The
    /// rule is enforced by [`Check::validate`] and asserted in tests, not left
    /// to review.
    pub fn requires_remedy(self) -> bool {
        self.is_failure() || self.is_warning()
    }

    /// The mark plus its separator, as a fixed five-column field so section
    /// blocks line up in both color and no-color mode.
    ///
    /// The separator is part of the field rather than the format string
    /// because the no-color labels are not all the same length: `WARN` fills
    /// four columns and `OK` two, so a single space in the caller renders
    /// `WARNDisabled` next to `OK  Running`.
    pub fn mark(self, color_enabled: bool) -> String {
        if color_enabled {
            let glyph = match self {
                State::Ok => color::checkmark(true).to_string(),
                State::Failed => color::cross(true).to_string(),
                State::NotApplicable => color::dim("\u{00b7}", true),
                _ => color::warning_mark(true).to_string(),
            };
            format!("{glyph}    ")
        } else {
            let label = match self {
                State::Ok => "OK   ",
                State::Failed => "ERR  ",
                State::NotApplicable => "--   ",
                _ => "WARN ",
            };
            label.to_string()
        }
    }
}

// ---------------------------------------------------------------------------
// Check
// ---------------------------------------------------------------------------

/// One diagnostic finding, belonging to exactly one [`Section`].
///
/// A section holds one or more of these; its state is the worst among them.
#[derive(Debug, Clone)]
pub struct Check {
    pub section: Section,
    pub state: State,
    /// One factual line. No remediation, no hedging.
    pub headline: String,
    /// Extra context lines, rendered indented under the headline.
    pub detail: Vec<String>,
    /// `OL-XXXX`. Required whenever [`State::requires_remedy`].
    pub code: Option<&'static str>,
    /// An exact command or edit. Required whenever [`State::requires_remedy`].
    pub remedy: Option<String>,
    /// Where the state came from — `config.toml:59`, `--no-persistence`,
    /// `keychain`. This is the field that turns "the boundary is off" into
    /// "the boundary is off *because of this line in this file*".
    pub source: Option<String>,
    /// Which agent this check is about — the CloudEvents `source` wire value
    /// (`"claude-code"`). `None` for a host-wide check that belongs to no
    /// single agent. Serialized only when set: absent, never `null`.
    pub agent: Option<&'static str>,
    /// Whether `headline` is still the one [`Check::unknown`] generated, which
    /// already names the blocker. Decides whether the block rendering adds the
    /// separate `waiting on :` line — without it, the default headline and that
    /// line said the same thing twice, one under the other.
    generated_headline: bool,
}

impl Check {
    fn new(section: Section, state: State, headline: impl Into<String>) -> Self {
        Self {
            section,
            state,
            headline: headline.into(),
            detail: Vec::new(),
            code: None,
            remedy: None,
            source: None,
            agent: None,
            generated_headline: false,
        }
    }

    /// Enabled and proven working.
    pub fn ok(section: Section, headline: impl Into<String>) -> Self {
        Self::new(section, State::Ok, headline)
    }

    /// Deliberately switched off.
    pub fn off(section: Section, headline: impl Into<String>) -> Self {
        Self::new(section, State::Off, headline)
    }

    /// Working but not at full capability.
    pub fn degraded(section: Section, headline: impl Into<String>) -> Self {
        Self::new(section, State::Degraded, headline)
    }

    /// Verification still in flight.
    pub fn pending(section: Section, headline: impl Into<String>) -> Self {
        Self::new(section, State::Pending, headline)
    }

    /// Enabled and not working.
    pub fn failed(section: Section, headline: impl Into<String>) -> Self {
        Self::new(section, State::Failed, headline)
    }

    /// Indeterminable because `blocker` failed. Carries its own code and
    /// remedy, so it satisfies the remedy rule without every call site
    /// repeating the same two strings.
    pub fn unknown(section: Section, blocker: Section) -> Self {
        Self {
            section,
            state: State::Unknown(blocker),
            headline: format!("Cannot check — waiting on {}", blocker.title()),
            detail: Vec::new(),
            code: Some(crate::error::ERR_SUBSYSTEM_DEGRADED),
            remedy: Some(format!(
                "Fix {} first, then run `openlatch doctor` again.",
                blocker.title()
            )),
            source: None,
            agent: None,
            generated_headline: true,
        }
    }

    /// Absent from the build or irrelevant on this platform.
    pub fn not_applicable(section: Section, headline: impl Into<String>) -> Self {
        Self::new(section, State::NotApplicable, headline)
    }

    /// Attach the `OL-XXXX` code.
    #[must_use]
    pub fn code(mut self, code: &'static str) -> Self {
        self.code = Some(code);
        self
    }

    /// Attach the exact command or edit that resolves this.
    #[must_use]
    pub fn remedy(mut self, remedy: impl Into<String>) -> Self {
        self.remedy = Some(remedy.into());
        self
    }

    /// Attach where the state came from.
    #[must_use]
    pub fn source(mut self, source: impl Into<String>) -> Self {
        self.source = Some(source.into());
        self
    }

    /// Replace the headline.
    ///
    /// Mostly for [`Check::unknown`], whose generated wording says only that
    /// something is blocked. In a section that also holds green checks, the
    /// compact one-line rendering shows the worst check — so "not determinable"
    /// with no subject reads as if nothing about the section is known, when in
    /// fact one cross-check out of four is waiting on the daemon.
    ///
    /// Overriding it moves the blocker onto its own line in the block
    /// rendering, so it is named exactly once either way.
    #[must_use]
    pub fn headline(mut self, headline: impl Into<String>) -> Self {
        self.headline = headline.into();
        self.generated_headline = false;
        self
    }

    /// Attach one context line.
    #[must_use]
    pub fn detail(mut self, line: impl Into<String>) -> Self {
        self.detail.push(line.into());
        self
    }

    /// Attach one context line when there is one, and nothing when there is not.
    ///
    /// For call sites holding an `Option<String>` a binding already answered —
    /// [`crate::hooks::binding::LivenessReport::detail`] is the one in the tree.
    #[must_use]
    pub fn detail_opt(mut self, line: Option<impl Into<String>>) -> Self {
        if let Some(line) = line {
            self.detail.push(line.into());
        }
        self
    }

    /// Attach the agent this check is about — the wire `agent_type()`.
    ///
    /// A check left unstamped is host-wide, and its JSON carries no `agent`
    /// key at all.
    #[must_use]
    pub fn agent(mut self, agent: &'static str) -> Self {
        self.agent = Some(agent);
        self
    }

    /// Why this check violates the contract, if it does.
    ///
    /// Returns `None` for a well-formed check. Used by [`Report::validate`],
    /// which every rendering path runs under `debug_assert`.
    pub fn validate(&self) -> Option<String> {
        if !self.state.requires_remedy() {
            return None;
        }
        match (self.code, &self.remedy) {
            (Some(_), Some(_)) => None,
            (None, Some(_)) => Some(format!(
                "{}: '{}' is {} but carries no OL-XXXX code",
                self.section.title(),
                self.headline,
                self.state.key()
            )),
            (Some(_), None) => Some(format!(
                "{}: '{}' is {} but carries no remedy",
                self.section.title(),
                self.headline,
                self.state.key()
            )),
            (None, None) => Some(format!(
                "{}: '{}' is {} but carries neither code nor remedy",
                self.section.title(),
                self.headline,
                self.state.key()
            )),
        }
    }

    pub fn to_json(&self) -> serde_json::Value {
        let mut value = serde_json::json!({
            "section": self.section.key(),
            "state": self.state.key(),
            "blocked_by": match self.state {
                State::Unknown(b) => Some(b.key()),
                _ => None,
            },
            // Kept for consumers written against the pre-contract `doctor
            // --json`, where `pass` meant "not a failure" and warnings counted
            // as passes. `state` carries the detail.
            "pass": !self.state.is_failure(),
            "headline": self.headline,
            "detail": self.detail,
            "code": self.code,
            "remedy": self.remedy,
            "source": self.source,
        });
        // Absent, never null: a host-wide check emits no `agent` key at all.
        if let (Some(agent), Some(object)) = (self.agent, value.as_object_mut()) {
            object.insert("agent".into(), serde_json::json!(agent));
        }
        value
    }
}

// ---------------------------------------------------------------------------
// Report
// ---------------------------------------------------------------------------

/// How the machine is doing, as one word.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Overall {
    /// Nothing failed, nothing warned.
    Healthy,
    /// Nothing failed, something warned.
    Degraded,
    /// Something failed.
    Broken,
}

impl Overall {
    pub fn key(self) -> &'static str {
        match self {
            Overall::Healthy => "healthy",
            Overall::Degraded => "degraded",
            Overall::Broken => "broken",
        }
    }

    fn label(self) -> &'static str {
        match self {
            Overall::Healthy => "HEALTHY",
            Overall::Degraded => "DEGRADED",
            Overall::Broken => "BROKEN",
        }
    }
}

/// Tally of check outcomes.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Counts {
    pub ok: usize,
    pub warned: usize,
    pub failed: usize,
}

/// An ordered set of [`Check`]s covering the install.
#[derive(Debug, Clone, Default)]
pub struct Report {
    checks: Vec<Check>,
}

impl Report {
    pub fn new() -> Self {
        Self::default()
    }

    /// Record one finding.
    pub fn push(&mut self, check: Check) {
        debug_assert!(
            check.validate().is_none(),
            "contract violation: {}",
            check.validate().unwrap_or_default()
        );
        self.checks.push(check);
    }

    /// Record one finding, chainable.
    #[must_use]
    pub fn with(mut self, check: Check) -> Self {
        self.push(check);
        self
    }

    /// Drop everything filed under `section` and file `check` instead.
    ///
    /// For the caller that knows something the detectors cannot: `init
    /// --no-start` deliberately leaves the daemon down, and a report that calls
    /// that a failure is describing the flag, not the machine.
    pub fn replace_section(&mut self, section: Section, check: Check) {
        self.checks.retain(|c| c.section != section);
        self.push(check);
    }

    pub fn is_empty(&self) -> bool {
        self.checks.is_empty()
    }

    pub fn checks(&self) -> &[Check] {
        &self.checks
    }

    /// Every check filed under `section`, in push order.
    pub fn section_checks(&self, section: Section) -> impl Iterator<Item = &Check> {
        self.checks.iter().filter(move |c| c.section == section)
    }

    /// The worst state among a section's checks.
    ///
    /// A section with no checks is [`State::NotApplicable`]: the caller either
    /// had nothing to say or the section is absent from the build. Sections are
    /// never silently dropped from the rendering — see [`Report::validate`].
    pub fn section_state(&self, section: Section) -> State {
        self.section_checks(section)
            .map(|c| c.state)
            .max_by_key(|s| s.severity())
            .unwrap_or(State::NotApplicable)
    }

    /// Tally across every check.
    pub fn counts(&self) -> Counts {
        let mut counts = Counts::default();
        for check in &self.checks {
            if check.state.is_failure() {
                counts.failed += 1;
            } else if check.state.is_warning() {
                counts.warned += 1;
            } else if check.state == State::Ok {
                counts.ok += 1;
            }
        }
        counts
    }

    pub fn overall(&self) -> Overall {
        let counts = self.counts();
        if counts.failed > 0 {
            Overall::Broken
        } else if counts.warned > 0 {
            Overall::Degraded
        } else {
            Overall::Healthy
        }
    }

    /// The process exit status this report implies.
    ///
    /// `0` healthy · [`EXIT_DEGRADED`] warnings only · `1` at least one
    /// failure.
    pub fn exit_code(&self) -> i32 {
        match self.overall() {
            Overall::Healthy => 0,
            Overall::Degraded => EXIT_DEGRADED,
            Overall::Broken => 1,
        }
    }

    /// Record [`Report::exit_code`] as the process verdict.
    pub fn record_verdict(&self) {
        record_exit_code(self.exit_code());
    }

    /// Every way this report violates the contract.
    ///
    /// Two rules: each non-`Ok`, non-`NotApplicable` check carries a code and a
    /// remedy, and all eleven sections are represented. Empty means conforming.
    pub fn validate(&self) -> Vec<String> {
        let mut problems: Vec<String> = self.checks.iter().filter_map(Check::validate).collect();
        for section in Section::ALL {
            if self.section_checks(section).next().is_none() {
                problems.push(format!(
                    "{} has no check — every section is always reported (P6)",
                    section.title()
                ));
            }
        }
        problems
    }

    /// The actionable half of every non-green check, ready to print under the
    /// section blocks.
    pub fn issues(&self) -> Vec<String> {
        self.checks
            .iter()
            .filter(|c| c.state.requires_remedy())
            .map(|c| {
                let mut line = format!("{}{}", c.section.title(), c.headline);
                if let Some(remedy) = &c.remedy {
                    line.push(' ');
                    line.push_str(remedy);
                }
                line
            })
            .collect()
    }

    // -----------------------------------------------------------------------
    // Rendering
    // -----------------------------------------------------------------------

    /// The full section-by-section rendering used by `doctor` and by the report
    /// half of `init`.
    ///
    /// A section holding exactly one `Ok` or `NotApplicable` check collapses to
    /// a single padded line; anything the operator might need to act on gets a
    /// full block with its source and remedy. The rule is mechanical, so the
    /// same state always renders the same way.
    pub fn render(&self, output: &OutputConfig) {
        debug_assert!(
            self.validate().is_empty(),
            "contract violations: {:?}",
            self.validate()
        );
        if output.format == OutputFormat::Json || output.quiet {
            return;
        }

        let counts = self.counts();
        let overall = self.overall();
        let headline = format!(
            "Overall: {}{} failed, {} warning{}, {} ok",
            overall.label(),
            counts.failed,
            counts.warned,
            if counts.warned == 1 { "" } else { "s" },
            counts.ok,
        );
        eprintln!(
            "{}",
            match overall {
                Overall::Healthy => color::green(&headline, output.color),
                Overall::Degraded => headline.clone(),
                Overall::Broken => color::red(&headline, output.color),
            }
        );
        eprintln!();

        // Three group headings, eleven section lines, and detail only where
        // something needs attention.
        //
        // The flat form gave every section its own heading, which is eleven
        // headings for twenty lines of content — and once the sections that
        // held a single check collapsed onto their title line, the marks
        // scattered across as many columns as there were title lengths.
        // Grouping fixes both: one scan column for the marks, and the green
        // sections fold into a line each, so what stays on screen is mostly
        // the things that do not pass. `--verbose` unfolds everything.
        for group in Group::ALL {
            eprintln!("{}", color::bold(group.title(), output.color));
            for section in Section::of_group(group) {
                self.render_section_line(section, output);
            }
            eprintln!();
        }
    }

    /// One section as a line under its group, plus whatever needs saying.
    ///
    /// A green section is a line. A section with anything else on it lists each
    /// non-green check, every mark in the same column, each followed by its own
    /// detail, source and remedy.
    fn render_section_line(&self, section: Section, output: &OutputConfig) {
        let state = self.section_state(section);
        let title_cell = format!("  {:<TITLE_WIDTH$}  ", section.title());
        // Blank cell of the same width, so a second finding in one section puts
        // its mark under the first rather than after the title.
        let blank_cell = " ".repeat(title_cell.len());

        let interesting: Vec<&Check> = if output.verbose {
            self.section_checks(section).collect()
        } else {
            self.section_checks(section)
                .filter(|c| c.state.requires_remedy())
                .collect()
        };

        if interesting.is_empty() {
            eprintln!(
                "{title_cell}{}{}",
                state.mark(output.color),
                self.section_summary(section)
            );
            return;
        }

        for (index, check) in interesting.iter().enumerate() {
            let cell = if index == 0 { &title_cell } else { &blank_cell };
            eprintln!(
                "{cell}{}{}{}",
                check.state.mark(output.color),
                check.headline,
                match check.code {
                    Some(code) if check.state.requires_remedy() =>
                        format!("   {}", color::dim(&format!("[{code}]"), output.color)),
                    _ => String::new(),
                }
            );
            self.render_continuations(check, &" ".repeat(title_cell.len() + MARK_WIDTH), output);
        }
    }

    /// The one line a section that needs no attention gets.
    ///
    /// A single check speaks for itself. Several collapse to a count — and the
    /// count separates "passed" from "not applicable", because a build without
    /// crash reporting has not passed a crash-reporting check, it has skipped
    /// one.
    fn section_summary(&self, section: Section) -> String {
        let checks: Vec<&Check> = self.section_checks(section).collect();
        match checks.as_slice() {
            [] => "no data".to_string(),
            [only] => only.headline.clone(),
            many => {
                let passed = many.iter().filter(|c| c.state == State::Ok).count();
                let skipped = many.len() - passed;
                if skipped == 0 {
                    format!("{passed} checks passed")
                } else {
                    format!("{passed} passed, {skipped} not applicable")
                }
            }
        }
    }

    /// A check's detail, source and remedy, at a caller-chosen indent.
    fn render_continuations(&self, check: &Check, indent: &str, output: &OutputConfig) {
        // Structural, not prose: an `Unknown` whose headline was replaced names
        // its blocker on its own line, so a reader — and a test — can rely on
        // the line rather than on a phrase surviving an edit. Skipped when the
        // headline is still the generated one, which already carries the
        // blocker; printing both put the same sentence twice.
        if let (State::Unknown(blocker), false) = (check.state, check.generated_headline) {
            eprintln!(
                "{indent}{}",
                color::dim(&format!("waiting on : {}", blocker.title()), output.color)
            );
        }
        for line in &check.detail {
            eprintln!("{indent}{}", color::dim(line, output.color));
        }
        if let Some(source) = &check.source {
            eprintln!(
                "{indent}{}",
                color::dim(&format!("found in : {source}"), output.color)
            );
        }
        if let Some(remedy) = &check.remedy {
            eprintln!(
                "{indent}{}",
                color::dim(&format!("to fix : {remedy}"), output.color)
            );
        }
    }

    /// Print one section's block — title, every check, sources and remedies.
    ///
    /// The building block behind both [`Report::render`] and the
    /// per-subsystem status commands, so `openlatch hooks status` and the Hooks
    /// block of `openlatch doctor` are the same text by construction.
    pub fn render_section(&self, section: Section, output: &OutputConfig) {
        if output.format == OutputFormat::Json || output.quiet {
            return;
        }
        eprintln!("{}", color::bold(section.title(), output.color));
        for check in self.section_checks(section) {
            eprintln!(
                "  {}{}{}",
                check.state.mark(output.color),
                check.headline,
                match check.code {
                    Some(code) if check.state.requires_remedy() =>
                        format!("   {}", color::dim(&format!("[{code}]"), output.color)),
                    _ => String::new(),
                }
            );
            self.render_continuations(check, CONTINUATION, output);
        }
    }

    /// One line per section, worst state wins — the `status` rendering.
    ///
    /// Carries no remedies on purpose: `status` is the glance, `doctor` is the
    /// diagnosis. A non-green section here points at `doctor`.
    pub fn render_compact(&self, output: &OutputConfig) {
        if output.format == OutputFormat::Json || output.quiet {
            return;
        }
        // Same groups and the same columns as `doctor`, one line per section
        // and nothing else. `status` is the glance; a reader who wants the
        // cause and the remedy is one command away, and told so.
        for group in Group::ALL {
            eprintln!("  {}", color::bold(group.title(), output.color));
            for section in Section::of_group(group) {
                let state = self.section_state(section);
                // The worst check is the one worth summarising; ties go to the
                // first pushed, which is the most fundamental by construction.
                let headline = if state.requires_remedy() {
                    self.section_checks(section)
                        .filter(|c| c.state == state)
                        .map(|c| c.headline.clone())
                        .next()
                        .unwrap_or_else(|| "no data".to_string())
                } else {
                    self.section_summary(section)
                };
                eprintln!(
                    "    {:<TITLE_WIDTH$}  {}{}",
                    section.title(),
                    state.mark(output.color),
                    headline
                );
            }
        }

        if self.overall() != Overall::Healthy {
            eprintln!();
            eprintln!("  Run `openlatch doctor` for causes and remedies.");
        }
    }

    /// The machine rendering. Isomorphic to the human one (P7).
    pub fn to_json(&self) -> serde_json::Value {
        let counts = self.counts();
        let sections: Vec<serde_json::Value> = Section::ALL
            .iter()
            .map(|section| {
                serde_json::json!({
                    "section": section.key(),
                    "group": section.group().key(),
                    "state": self.section_state(*section).key(),
                    "summary": self.section_summary(*section),
                    "checks": self
                        .section_checks(*section)
                        .map(Check::to_json)
                        .collect::<Vec<_>>(),
                })
            })
            .collect();

        serde_json::json!({
            "overall": self.overall().key(),
            "exit_code": self.exit_code(),
            "groups": Group::ALL
                .iter()
                .map(|g| serde_json::json!({
                    "group": g.key(),
                    "sections": Section::of_group(*g)
                        .map(|s| s.key())
                        .collect::<Vec<_>>(),
                }))
                .collect::<Vec<_>>(),
            "summary": {
                "ok": counts.ok,
                "warned": counts.warned,
                "failed": counts.failed,
            },
            "sections": sections,
            "issues": self.issues(),
        })
    }
}

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

    fn plain() -> OutputConfig {
        OutputConfig {
            format: OutputFormat::Human,
            verbose: false,
            debug: false,
            quiet: true, // rendering is exercised separately; keep tests silent
            color: false,
        }
    }

    /// Fill every section with a passing check so a test can then override the
    /// one section it cares about.
    fn all_green() -> Report {
        let mut report = Report::new();
        for section in Section::ALL {
            report.push(Check::ok(section, "fine"));
        }
        report
    }

    #[test]
    fn a_healthy_report_exits_zero() {
        let report = all_green();
        assert_eq!(report.overall(), Overall::Healthy);
        assert_eq!(report.exit_code(), 0);
    }

    #[test]
    fn a_disabled_feature_warns_and_exits_two() {
        let mut report = all_green();
        report.push(
            Check::off(Section::Boundary, "Disabled in config")
                .code(crate::error::ERR_BOUNDARY_NOT_RUNNING)
                .remedy("set [boundary] enabled = true, then `openlatch restart`"),
        );
        assert_eq!(report.section_state(Section::Boundary), State::Off);
        assert_eq!(report.overall(), Overall::Degraded);
        assert_eq!(report.exit_code(), EXIT_DEGRADED);
    }

    #[test]
    fn a_failure_outranks_a_warning() {
        let mut report = all_green();
        report.push(
            Check::off(Section::Persistence, "Disabled")
                .code(crate::error::ERR_NO_SUPERVISOR)
                .remedy("`openlatch supervision enable`"),
        );
        report.push(
            Check::failed(Section::Boundary, "Cannot bind 7600")
                .code(crate::error::ERR_BOUNDARY_PORT_IN_USE)
                .remedy("free the port"),
        );
        assert_eq!(report.overall(), Overall::Broken);
        assert_eq!(report.exit_code(), 1);
    }

    #[test]
    fn a_section_takes_the_worst_state_of_its_checks() {
        let mut report = all_green();
        report.push(Check::ok(Section::Daemon, "port bound"));
        report.push(
            Check::degraded(Section::Daemon, "one subsystem restarting")
                .code(crate::error::ERR_SUBSYSTEM_DEGRADED)
                .remedy("check the daemon log"),
        );
        assert_eq!(report.section_state(Section::Daemon), State::Degraded);
    }

    #[test]
    fn every_non_ok_check_carries_a_code_and_a_remedy() {
        // The rule, exercised over every constructor that can produce a
        // remedy-requiring state.
        let offenders = [
            Check::off(Section::Cloud, "x"),
            Check::degraded(Section::Cloud, "x"),
            Check::pending(Section::Cloud, "x"),
            Check::failed(Section::Cloud, "x"),
        ];
        for check in offenders {
            assert!(
                check.validate().is_some(),
                "{} without code/remedy must be rejected",
                check.state.key()
            );
        }
        // `unknown` supplies its own, so it is well-formed out of the box.
        assert!(Check::unknown(Section::Cloud, Section::Daemon)
            .validate()
            .is_none());
        // As are the two states that need no action.
        assert!(Check::ok(Section::Cloud, "x").validate().is_none());
        assert!(Check::not_applicable(Section::Cloud, "x")
            .validate()
            .is_none());
    }

    #[test]
    fn a_dead_daemon_produces_exactly_one_failure() {
        // Anti-cascade: the daemon fails, the seven sections behind it report
        // Unknown, and the report still shows a single cross.
        let mut report = Report::new();
        report.push(Check::ok(Section::Environment, "fine"));
        report.push(
            Check::failed(Section::Daemon, "not running")
                .code(crate::error::ERR_DAEMON_START_FAILED)
                .remedy("`openlatch start`"),
        );
        for section in [
            Section::Hooks,
            Section::Boundary,
            Section::Connection,
            Section::Cloud,
            Section::Policy,
            Section::Inventory,
            Section::Integrity,
        ] {
            report.push(Check::unknown(section, Section::Daemon));
        }
        report.push(Check::ok(Section::Persistence, "fine"));
        report.push(Check::not_applicable(Section::Telemetry, "opt-out"));
        report.push(Check::ok(Section::Update, "current"));

        assert_eq!(report.counts().failed, 1);
        assert_eq!(report.overall(), Overall::Broken);
        assert!(report.validate().is_empty(), "{:?}", report.validate());
    }

    #[test]
    fn validate_rejects_a_missing_section() {
        let mut report = Report::new();
        report.push(Check::ok(Section::Daemon, "fine"));
        let problems = report.validate();
        assert!(
            problems.iter().any(|p| p.contains("Boundary")),
            "a missing section must be reported: {problems:?}"
        );
    }

    #[test]
    fn every_section_belongs_to_exactly_one_non_empty_group() {
        // The taxonomy has to partition the sections: a section in no group
        // would vanish from the rendering, and an empty group would print a
        // heading with nothing under it.
        let grouped: Vec<Section> = Group::ALL
            .iter()
            .flat_map(|g| Section::of_group(*g))
            .collect();
        assert_eq!(
            grouped.len(),
            Section::ALL.len(),
            "every section belongs to exactly one group"
        );
        for group in Group::ALL {
            assert!(
                Section::of_group(group).next().is_some(),
                "{} has no sections",
                group.title()
            );
        }
    }

    #[test]
    fn section_order_follows_group_order() {
        // The rendering walks groups and then sections; `Section::ALL` is what
        // the JSON walks. If the two disagree, a reader comparing `doctor` with
        // `doctor --json` sees the same sections in two different orders.
        let grouped: Vec<Section> = Group::ALL
            .iter()
            .flat_map(|g| Section::of_group(*g))
            .collect();
        assert_eq!(grouped, Section::ALL.to_vec());
    }

    #[test]
    fn a_green_section_collapses_and_a_problem_does_not() {
        let mut report = Report::new();
        for section in Section::ALL {
            report.push(Check::ok(section, "fine"));
        }
        report.push(Check::ok(Section::Hooks, "also fine"));
        assert_eq!(
            report.section_summary(Section::Hooks),
            "2 checks passed",
            "several green checks collapse to a count"
        );
        assert_eq!(
            report.section_summary(Section::Daemon),
            "fine",
            "a lone check speaks for itself"
        );

        // "Passed" and "skipped" are different claims: a build without crash
        // reporting has not passed a crash-reporting check.
        report.push(Check::not_applicable(Section::Update, "not compiled in"));
        assert_eq!(
            report.section_summary(Section::Update),
            "1 passed, 1 not applicable"
        );
    }

    #[test]
    fn human_and_json_carry_the_same_sections() {
        let report = all_green();
        let json = report.to_json();
        let sections = json["sections"].as_array().expect("sections array");
        assert_eq!(sections.len(), Section::ALL.len());
        for (rendered, expected) in sections.iter().zip(Section::ALL) {
            assert_eq!(rendered["section"], expected.key());
        }
    }

    #[test]
    fn json_keeps_the_legacy_pass_field_meaning_not_a_failure() {
        let warn = Check::off(Section::Boundary, "off")
            .code(crate::error::ERR_BOUNDARY_NOT_RUNNING)
            .remedy("x");
        assert_eq!(warn.to_json()["pass"], serde_json::Value::Bool(true));
        let fail = Check::failed(Section::Boundary, "broken")
            .code(crate::error::ERR_BOUNDARY_PORT_IN_USE)
            .remedy("x");
        assert_eq!(fail.to_json()["pass"], serde_json::Value::Bool(false));
    }

    #[test]
    fn check_agent_is_absent_not_null_when_unset() {
        // A host-wide check emits no `agent` key at all — an unconditional
        // `"agent": null` on every check would move the JSON of every existing
        // consumer, which is what the byte-diff gate exists to catch.
        let host_wide = Check::ok(Section::Boundary, "listening");
        let json = host_wide.to_json();
        assert!(
            json.get("agent").is_none(),
            "an unstamped check must carry no `agent` key, not a null one: {json}"
        );

        let stamped = Check::ok(Section::Hooks, "installed").agent("claude-code");
        assert_eq!(stamped.to_json()["agent"], serde_json::json!("claude-code"));
    }

    #[test]
    fn a_blocker_is_named_exactly_once() {
        // Two renderings, one fact. The generated headline carries the blocker
        // and the structural line is suppressed; an overridden headline says
        // something more useful and the structural line supplies the blocker.
        let generated = Check::unknown(Section::Policy, Section::Cloud);
        assert!(
            generated.headline.contains("Cloud"),
            "the generated headline must name the blocker for the compact view"
        );
        assert!(
            generated.generated_headline,
            "an untouched `unknown` keeps its generated headline"
        );

        let overridden = Check::unknown(Section::Policy, Section::Cloud)
            .headline("Enforcement state unknown — the platform is unreachable");
        assert!(
            !overridden.generated_headline,
            "overriding the headline hands the blocker to the structural line"
        );
        assert!(
            !overridden.headline.contains("Cloud"),
            "an overridden headline is free not to repeat the blocker"
        );
    }

    #[test]
    fn marks_are_five_columns_wide_in_no_color_mode() {
        for state in [
            State::Ok,
            State::Off,
            State::Degraded,
            State::Pending,
            State::Failed,
            State::Unknown(Section::Daemon),
            State::NotApplicable,
        ] {
            assert_eq!(state.mark(false).len(), 5, "{:?} misaligns", state);
        }
    }

    #[test]
    fn the_recorded_verdict_keeps_the_worst_code() {
        // Severity, not numeric order: a failure must survive a later warning.
        reset_exit_code();
        record_exit_code(EXIT_DEGRADED);
        record_exit_code(1);
        assert_eq!(pending_exit_code(), 1, "failure outranks degraded");

        reset_exit_code();
        record_exit_code(1);
        record_exit_code(EXIT_DEGRADED);
        assert_eq!(pending_exit_code(), 1, "degraded cannot clear a failure");

        reset_exit_code();
        record_exit_code(EXIT_DEGRADED);
        record_exit_code(0);
        assert_eq!(
            pending_exit_code(),
            EXIT_DEGRADED,
            "success cannot clear a warning"
        );

        reset_exit_code();
        assert_eq!(pending_exit_code(), 0);
    }

    #[test]
    fn rendering_is_silent_in_quiet_mode() {
        // Not an output assertion — a smoke test that the guarded paths do not
        // panic on a fully-populated report.
        let report = all_green();
        report.render(&plain());
        report.render_compact(&plain());
    }
}