cleanlib-client 0.3.0

HTTP client SDK for the CleanLibrary verdict API — VerdictEnvelopeV1 types, derive_status logic, transport, config, and risk-acceptance YAML emitter shared between cleanlib-cli and other CleanLibrary consumers.
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
//! CLEANLIB-178 — canonical customer-facing state taxonomy (Rust surfaces).
//!
//! Single source of truth for the **8 customer states** that the malicious-vs-
//! vulnerable cluster (CLEANLIB-176 wire-shape + 177 policy overlay + 178
//! aesthetic) surfaces. The design contract lives at
//! `decisions/2026-06-12-cleanlib-178-state-aesthetic-mapping.md`; this module
//! is its executable form for the Rust render surfaces — `cleanlib-cli`,
//! `cleanlib-lsp` (CLEANLIB-209), and any consumer of `cleanlib-client`. The
//! TS extension / Python MCP / JS+Go+Py SDKs mirror this table in their own
//! languages, each with a contract test asserting the same wire→state map
//! (anti-drift, sister of the silent-schema-drift discipline).
//!
//! ## Why this lives in `cleanlib-client`, not `cleanlib-core`
//!
//! `cleanlib-core` is `publish = false`; the customer-state taxonomy is a
//! *presentation* concern consumed only by published render surfaces (the App
//! emits the wire `source`; it never renders a customer state). Keying on the
//! wire string (`Verdict.source: String`) — rather than `cleanlib-core`'s
//! `VerdictSource` enum — keeps this crate publishable to crates.io and avoids
//! a render-side dependency on the service-internal core crate.
//!
//! ## Design rules baked in (§0 of the spec — non-negotiable)
//!
//! 1. **Customer-language only** — wire/engine codenames never appear in
//!    `label()` / `copy()`.
//! 2. **Soft severity tokens** (dark-theme-safe); brand cyan `#50C0E0` is
//!    reserved for CLEAN.
//! 3. **Three derive tiers** (block / warn / clean) → exit codes (1 / 2 / 0).
//!
//! ## Derive-once + fail-closed
//!
//! Derive the state ONCE from the wire `source` ([`CustomerState::from_wire`]).
//! The App applies severity precedence server-side when it picks the single
//! `source`, so this map is 1:1 — no precedence is re-implemented here. An
//! unrecognized / future `source` fails CLOSED to `NotYetAssessed` (warn,
//! needs-review) — never silently Clean.

/// The three derive tiers — drive exit codes (block=1, warn=2, clean=0) and
/// the colour family, and map onto the universal ALLOW/WARN/DENY render bucket.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Tier {
    /// exit 1 — DENY. Customer must not install / must remove.
    Block,
    /// exit 2 — WARN. Review / upgrade (fail-closed for unknown).
    Warn,
    /// exit 0 — ALLOW. No known issues.
    Clean,
}

impl Tier {
    /// Process exit code for the CLI gate (block=1, warn=2, clean=0).
    pub fn exit_code(self) -> i32 {
        match self {
            Tier::Block => 1,
            Tier::Warn => 2,
            Tier::Clean => 0,
        }
    }
}

/// The 9 canonical customer-facing states, severity order (highest first) per
/// the BD-ratified ordering in §1: Blocked-by-policy, Compromised, Malicious,
/// Ransomware-linked, Actively-exploited, Vulnerable, Range-not-resolved,
/// Not-yet-assessed, Clean. CLEANLIB-518(§3) added Range-not-resolved (8→9).
// CLEANLIB-657 (CX-8): #[non_exhaustive] forces external consumers to include a
// wildcard arm, so a future state can never be silently mis-handled — and, with
// NotYetAssessed/RangeNotResolved as their own variants, a caller can NEVER
// accidentally treat 'not assessed' as allowed. Uncertainty lives in the type.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CustomerState {
    /// Customer's OWN policy rule blocked this package (operative gate).
    BlockedByPolicy,
    /// Tampered-with in a supply-chain attack (curated compromise list).
    Compromised,
    /// Known-malicious package (malware / typosquat).
    Malicious,
    /// Vulnerability tied to active ransomware campaigns.
    RansomwareLinked,
    /// Vulnerability being exploited in the wild (CISA KEV).
    ActivelyExploited,
    /// Has known CVEs (review + upgrade).
    Vulnerable,
    /// CLEANLIB-518 (§3): the requested semver range could not be resolved to a
    /// concrete version (`source_state = RANGE_NOT_RESOLVED`). Distinct from
    /// `NotYetAssessed` — the package is not un-assessed, the *range* is; the
    /// customer must pin an exact version. Fail-closed needs-input (Warn).
    RangeNotResolved,
    /// No verdict on file yet — fail-closed needs-review.
    NotYetAssessed,
    /// No known issues found.
    Clean,
}

impl CustomerState {
    /// Derive the customer state from the wire `source` string (the values in
    /// `crate::envelope::ALL_VERDICT_SOURCES`). Unknown / future variants fail
    /// CLOSED to `NotYetAssessed` (warn) — never silently Clean.
    ///
    /// Two variants carry a note:
    /// - `DM_THRESHOLD_BLOCK` → `BlockedByPolicy` (the customer's own rule).
    ///   The spec also routes a `DM_THRESHOLD_BLOCK` from the *curated*
    ///   supply-chain-compromise list (CLEANLIB-177) to `Compromised`, but that
    ///   distinction is carried by which rule fired, not by `source` alone, and
    ///   177 is not yet shipped. Until 177 lands + the App tags curated-list
    ///   blocks, every `DM_THRESHOLD_BLOCK` is the customer's policy. See
    ///   [`from_block_origin`](CustomerState::from_block_origin).
    /// - `VECTOR_VERDICT` is the legacy pre-176 full-eval source, preserved for
    ///   backward-compat. Post-176 the App projects findings into the specific
    ///   `CVE_FINDING*` variants, so a bare `VECTOR_VERDICT` reaching a render
    ///   surface is a legacy non-clean signal → `Vulnerable` (fail-safe).
    pub fn from_wire(source: &str) -> CustomerState {
        match source {
            "ALLOWED_NO_FINDINGS" => CustomerState::Clean,
            "CVE_FINDING" => CustomerState::Vulnerable,
            "CVE_FINDING_ON_KEV" => CustomerState::ActivelyExploited,
            "CVE_FINDING_ON_RANSOMWARE" => CustomerState::RansomwareLinked,
            "MALICIOUS_TRIAGE" => CustomerState::Malicious,
            "DM_THRESHOLD_BLOCK" => CustomerState::BlockedByPolicy,
            "INSUFFICIENT_DATA" => CustomerState::NotYetAssessed,
            // Legacy backward-compat — fail-safe to Vulnerable, never Clean.
            "VECTOR_VERDICT" => CustomerState::Vulnerable,
            // Unknown / future variant — fail CLOSED to needs-review.
            _ => CustomerState::NotYetAssessed,
        }
    }

    /// Same as [`from_wire`](CustomerState::from_wire) but lets the caller
    /// resolve the `DM_THRESHOLD_BLOCK` ambiguity when it knows the block
    /// origin. Use once CLEANLIB-177 ships and the App tags curated-list
    /// blocks: `curated_compromise = true` routes `DM_THRESHOLD_BLOCK` to
    /// `Compromised` instead of `BlockedByPolicy`.
    pub fn from_block_origin(source: &str, curated_compromise: bool) -> CustomerState {
        match (source, curated_compromise) {
            ("DM_THRESHOLD_BLOCK", true) => CustomerState::Compromised,
            _ => CustomerState::from_wire(source),
        }
    }

    /// CLEANLIB-518 (§3): resolve the customer state taking the wire
    /// `source_state` into account. A `RANGE_NOT_RESOLVED` source_state
    /// (CLEANLIB-513 — App could not resolve the requested semver range) maps to
    /// `RangeNotResolved` so the render banner reads "Range not resolved" and
    /// agrees with the reasoning body, instead of collapsing to the generic
    /// `NotYetAssessed` banner. All other source_states defer to
    /// [`from_wire`](CustomerState::from_wire) on `source`.
    pub fn from_wire_with_source_state(source: &str, source_state: Option<&str>) -> CustomerState {
        match source_state {
            // `RANGE_NOT_RESOLVED` (CLEANLIB-513/§3) is a source_state-only value
            // — not a VerdictSource `from_wire` knows — so it keeps its explicit
            // arm.
            Some(s) if s.eq_ignore_ascii_case("RANGE_NOT_RESOLVED") => {
                CustomerState::RangeNotResolved
            }
            // CLEANLIB-543: `source_state` is the envelope-v2 canonical status key
            // (the v2 rename of `source`, carrying the refined origin —
            // CVE_FINDING_ON_KEV / CVE_FINDING_ON_RANSOMWARE / MALICIOUS_TRIAGE /
            // …). When present, derive from IT, not the coarse `source` (which the
            // App may emit as a flat VECTOR_VERDICT on the v2 shape). This is what
            // keeps `actively_exploited` / `ransomware_linked` from flattening to
            // `vulnerable` when the origin rides in source_state. `from_wire`
            // already maps the full VerdictSource corpus and fail-closes an
            // unknown value to `not_yet_assessed`, so this stays fail-safe. Note
            // the App emits `customer_state == from_wire(source_state)` server-side
            // (§3), so preferring source_state is equivalent to trusting the
            // pre-resolved customer_state.
            Some(s) if !s.is_empty() => CustomerState::from_wire(s),
            // v1 back-compat: no source_state → the origin rides in `source`.
            _ => CustomerState::from_wire(source),
        }
    }

    /// CLEANLIB-855: same as [`from_wire_with_source_state`], PLUS resolves
    /// the `DM_THRESHOLD_BLOCK` → `Compromised` distinction via
    /// [`from_block_origin`] when `matched_rule_id` names a curated
    /// supply-chain-compromise-bridge rule (see
    /// [`is_curated_supply_chain_compromise`]).
    ///
    /// This is the render call sites' entry point once the App threads
    /// `matched_rule_id` onto the wire (CLEANLIB-855) — before that field
    /// existed, [`from_wire_with_source_state`] was the only option and
    /// `Compromised` was permanently unreachable from any real verdict
    /// (only unit tests ever constructed it directly).
    pub fn from_wire_with_source_state_and_origin(
        source: &str,
        source_state: Option<&str>,
        matched_rule_id: Option<&str>,
    ) -> CustomerState {
        if is_curated_supply_chain_compromise(matched_rule_id) {
            // `from_block_origin` only special-cases `DM_THRESHOLD_BLOCK` —
            // resolve against whichever of source_state/source actually
            // carries that token (same precedence as
            // `from_wire_with_source_state`), THEN apply the curated-origin
            // override on top.
            let effective_source = match source_state {
                Some(s) if !s.is_empty() => s,
                _ => source,
            };
            return CustomerState::from_block_origin(effective_source, true);
        }
        CustomerState::from_wire_with_source_state(source, source_state)
    }

    /// Stable machine string for `--output json` `state` field + structured
    /// MCP/SDK fields. snake_case, customer-vocabulary, NOT the wire variant.
    pub fn as_str(self) -> &'static str {
        match self {
            CustomerState::BlockedByPolicy => "blocked_by_policy",
            CustomerState::Compromised => "compromised",
            CustomerState::Malicious => "malicious",
            CustomerState::RansomwareLinked => "ransomware_linked",
            CustomerState::ActivelyExploited => "actively_exploited",
            CustomerState::Vulnerable => "vulnerable",
            CustomerState::RangeNotResolved => "range_not_resolved",
            CustomerState::NotYetAssessed => "not_yet_assessed",
            CustomerState::Clean => "clean",
        }
    }

    /// Customer-facing display label (Title-case, no codenames). §2 of spec.
    pub fn label(self) -> &'static str {
        match self {
            CustomerState::BlockedByPolicy => "Blocked by policy",
            CustomerState::Compromised => "Compromised",
            CustomerState::Malicious => "Malicious",
            CustomerState::RansomwareLinked => "Ransomware-linked",
            CustomerState::ActivelyExploited => "Actively exploited",
            CustomerState::Vulnerable => "Vulnerable",
            CustomerState::RangeNotResolved => "Range not resolved",
            CustomerState::NotYetAssessed => "Not yet assessed",
            CustomerState::Clean => "Clean",
        }
    }

    /// One-line, action-first customer copy (no codenames, no raw tier words).
    /// §2 of spec — verbatim.
    pub fn copy(self) -> &'static str {
        match self {
            CustomerState::BlockedByPolicy => {
                "Blocked by your organization's policy. Contact your security \
                 owner or request an exception."
            }
            CustomerState::Compromised => {
                "This version was tampered with in a supply-chain attack. Do \
                 not install — use a known-good version."
            }
            CustomerState::Malicious => {
                "Known-malicious package (malware / typosquat). Do not install."
            }
            CustomerState::RansomwareLinked => {
                "Carries a vulnerability tied to active ransomware campaigns. \
                 Upgrade before shipping."
            }
            CustomerState::ActivelyExploited => {
                "Has a vulnerability that's being exploited in the wild (on the \
                 U.S. CISA exploited list). Upgrade urgently."
            }
            CustomerState::Vulnerable => {
                "Has known vulnerabilities (CVEs). Review and upgrade to a \
                 fixed version."
            }
            CustomerState::RangeNotResolved => {
                "The requested version range couldn't be resolved to a concrete \
                 version. Pin an exact version and re-check."
            }
            CustomerState::NotYetAssessed => {
                "No verdict on file yet — treat as needs-review until assessed."
            }
            CustomerState::Clean => "No known issues found.",
        }
    }

    /// Derive tier (block / warn / clean). `NotYetAssessed` is fail-closed →
    /// Warn. Per §1 "Tier" column.
    pub fn tier(self) -> Tier {
        match self {
            CustomerState::BlockedByPolicy
            | CustomerState::Compromised
            | CustomerState::Malicious
            | CustomerState::RansomwareLinked
            | CustomerState::ActivelyExploited => Tier::Block,
            CustomerState::Vulnerable
            | CustomerState::RangeNotResolved
            | CustomerState::NotYetAssessed => Tier::Warn,
            CustomerState::Clean => Tier::Clean,
        }
    }

    /// Process exit code for the CLI gate.
    pub fn exit_code(self) -> i32 {
        self.tier().exit_code()
    }

    /// The "needs-input" family: warn-tier states that are NOT a security
    /// finding but a gap the customer must resolve themselves — either no
    /// verdict is on file yet (`NotYetAssessed`) or the requested version range
    /// could not be resolved to a concrete version (`RangeNotResolved`,
    /// CLEANLIB-518). Both share the `--cl-unknown` colour token + `❔` glyph
    /// (§5). Render surfaces that distinguish "we found a problem" from "we
    /// need input" — e.g. the LSP diagnostic severity, which shows this family
    /// as INFORMATION rather than a WARNING finding — key on this predicate, so
    /// a future needs-input state is threaded in ONE canonical place rather than
    /// re-listed per surface (sister of the silent-drift discipline).
    pub fn is_needs_input(self) -> bool {
        matches!(
            self,
            CustomerState::NotYetAssessed | CustomerState::RangeNotResolved
        )
    }

    /// CSS custom-property name for the soft severity token (extension + SDKs
    /// consume these for theming). §1 "Soft colour token" column.
    pub fn color_token(self) -> &'static str {
        match self {
            CustomerState::BlockedByPolicy => "--cl-policy",
            CustomerState::Compromised => "--cl-compromised",
            CustomerState::Malicious => "--cl-malicious",
            CustomerState::RansomwareLinked => "--cl-ransomware",
            CustomerState::ActivelyExploited => "--cl-exploited",
            CustomerState::Vulnerable => "--cl-vulnerable",
            // §5 reuse: range-not-resolved shares the needs-input token family;
            // states differentiate by label, not a bespoke colour.
            CustomerState::RangeNotResolved => "--cl-unknown",
            CustomerState::NotYetAssessed => "--cl-unknown",
            CustomerState::Clean => "--cl-clean",
        }
    }

    /// Soft severity hex (draft-ratified working palette, §5). Brand cyan for
    /// Clean; distinct mauve for policy so "your rule" reads apart from "our
    /// finding" reds.
    pub fn color_hex(self) -> &'static str {
        match self {
            CustomerState::BlockedByPolicy => "#C77DBB",
            CustomerState::Compromised => "#D16D6A",
            CustomerState::Malicious => "#D9534F",
            CustomerState::RansomwareLinked => "#DB7B57",
            CustomerState::ActivelyExploited => "#E0934A",
            CustomerState::Vulnerable => "#D9A441",
            CustomerState::RangeNotResolved => "#7C8696",
            CustomerState::NotYetAssessed => "#7C8696",
            CustomerState::Clean => "#50C0E0",
        }
    }

    /// Text-surface emoji for MCP `human_message` + CLI text output. §1
    /// "MCP/CLI emoji" column. One concept per tier; states differentiate by
    /// label + colour, not a bespoke glyph family (§5 — reuse, don't cut).
    pub fn emoji(self) -> &'static str {
        match self {
            CustomerState::BlockedByPolicy => "🛑",
            CustomerState::Compromised => "",
            CustomerState::Malicious => "",
            CustomerState::RansomwareLinked => "🔴",
            CustomerState::ActivelyExploited => "🔴",
            CustomerState::Vulnerable => "⚠️",
            CustomerState::RangeNotResolved => "",
            CustomerState::NotYetAssessed => "",
            CustomerState::Clean => "",
        }
    }

    /// All 9 states, severity order (highest first). For exhaustive contract
    /// tests + doc generation. CLEANLIB-518(§3) added RangeNotResolved (8→9).
    pub fn all() -> [CustomerState; 9] {
        [
            CustomerState::BlockedByPolicy,
            CustomerState::Compromised,
            CustomerState::Malicious,
            CustomerState::RansomwareLinked,
            CustomerState::ActivelyExploited,
            CustomerState::Vulnerable,
            CustomerState::RangeNotResolved,
            CustomerState::NotYetAssessed,
            CustomerState::Clean,
        ]
    }
}

/// CLEANLIB-855: `true` iff `matched_rule_id` names a curated
/// supply-chain-compromise-bridge policy rule (the App-side prefix
/// convention for the CLEANLIB-177 curated compromise list), rather than an
/// ordinary customer policy rule. This is the one place that prefix
/// convention is checked on the render side — callers should go through this
/// function (or [`CustomerState::from_wire_with_source_state_and_origin`]
/// directly) rather than re-implementing the `starts_with` check, so the
/// convention only needs to change in one place if it ever does.
pub fn is_curated_supply_chain_compromise(matched_rule_id: Option<&str>) -> bool {
    matched_rule_id
        .map(|id| id.starts_with("supply-chain-compromise-bridge-"))
        .unwrap_or(false)
}

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

    // ── The wire→state mappings (the cross-surface contract) ────────────────
    #[test]
    fn wire_to_state_mapping_is_canonical() {
        use CustomerState::*;
        assert_eq!(CustomerState::from_wire("ALLOWED_NO_FINDINGS"), Clean);
        assert_eq!(CustomerState::from_wire("CVE_FINDING"), Vulnerable);
        assert_eq!(CustomerState::from_wire("CVE_FINDING_ON_KEV"), ActivelyExploited);
        assert_eq!(CustomerState::from_wire("CVE_FINDING_ON_RANSOMWARE"), RansomwareLinked);
        assert_eq!(CustomerState::from_wire("MALICIOUS_TRIAGE"), Malicious);
        assert_eq!(CustomerState::from_wire("DM_THRESHOLD_BLOCK"), BlockedByPolicy);
        assert_eq!(CustomerState::from_wire("INSUFFICIENT_DATA"), NotYetAssessed);
        assert_eq!(CustomerState::from_wire("VECTOR_VERDICT"), Vulnerable);
    }

    #[test]
    fn every_known_wire_source_maps_without_falling_through() {
        // Anti-drift: every value the envelope declares must have an explicit
        // mapping (not silently hit the fail-closed `_` arm). If 176/177 adds
        // a wire source, this fails until the map is extended.
        for &src in ALL_VERDICT_SOURCES {
            let state = CustomerState::from_wire(src);
            // ALLOWED_NO_FINDINGS is the only known source that may be Clean.
            if src != "ALLOWED_NO_FINDINGS" {
                assert_ne!(
                    state,
                    CustomerState::Clean,
                    "known non-clean source {src} mapped to Clean"
                );
            }
        }
    }

    #[test]
    fn cleanlib_518_range_not_resolved_source_state_maps_distinctly() {
        // §3: a RANGE_NOT_RESOLVED source_state yields the distinct
        // RangeNotResolved state (not the generic NotYetAssessed), so the CLI
        // banner label agrees with the reasoning body. Case-insensitive.
        assert_eq!(
            CustomerState::from_wire_with_source_state("INSUFFICIENT_DATA", Some("RANGE_NOT_RESOLVED")),
            CustomerState::RangeNotResolved
        );
        assert_eq!(
            CustomerState::from_wire_with_source_state("INSUFFICIENT_DATA", Some("range_not_resolved")),
            CustomerState::RangeNotResolved
        );
        // Banner↔body coherence: the label is no longer "Not yet assessed".
        assert_eq!(CustomerState::RangeNotResolved.label(), "Range not resolved");
        assert_ne!(
            CustomerState::RangeNotResolved.label(),
            CustomerState::NotYetAssessed.label()
        );
        // Fail-closed: an unresolved range is a WARN, never an ALLOW.
        assert_eq!(CustomerState::RangeNotResolved.exit_code(), 2);
        // No source_state (or a different one) still defers to `source`.
        assert_eq!(
            CustomerState::from_wire_with_source_state("CVE_FINDING", None),
            CustomerState::Vulnerable
        );
        assert_eq!(
            CustomerState::from_wire_with_source_state("CVE_FINDING", Some("CVE_FINDING")),
            CustomerState::Vulnerable
        );
    }

    #[test]
    fn unknown_source_fails_closed_to_needs_review() {
        assert_eq!(CustomerState::from_wire("SOME_FUTURE_VARIANT"), CustomerState::NotYetAssessed);
        assert_eq!(CustomerState::from_wire(""), CustomerState::NotYetAssessed);
        assert_ne!(CustomerState::from_wire("SOME_FUTURE_VARIANT"), CustomerState::Clean);
    }

    #[test]
    fn curated_compromise_routes_dm_block_to_compromised() {
        assert_eq!(
            CustomerState::from_block_origin("DM_THRESHOLD_BLOCK", true),
            CustomerState::Compromised
        );
        assert_eq!(
            CustomerState::from_block_origin("DM_THRESHOLD_BLOCK", false),
            CustomerState::BlockedByPolicy
        );
        assert_eq!(
            CustomerState::from_block_origin("CVE_FINDING", true),
            CustomerState::Vulnerable
        );
    }

    #[test]
    fn tier_and_exit_codes() {
        assert_eq!(CustomerState::Clean.exit_code(), 0);
        assert_eq!(CustomerState::Vulnerable.exit_code(), 2);
        assert_eq!(CustomerState::NotYetAssessed.exit_code(), 2); // fail-closed
        for s in [
            CustomerState::ActivelyExploited,
            CustomerState::RansomwareLinked,
            CustomerState::Malicious,
            CustomerState::Compromised,
            CustomerState::BlockedByPolicy,
        ] {
            assert_eq!(s.exit_code(), 1, "{s:?} must be block-tier");
        }
    }

    #[test]
    fn no_internal_codenames_in_customer_strings() {
        let banned = [
            "Vector", "VECTOR", "Tricorder", "DmThreshold", "DM_THRESHOLD",
            "CveFinding", "CVE_FINDING", "MaliciousTriage", "MALICIOUS_TRIAGE",
            "InsufficientData", "INSUFFICIENT_DATA", "vuln_xref", "mock", "fixture",
        ];
        for s in CustomerState::all() {
            for text in [s.label(), s.copy()] {
                for b in banned {
                    assert!(
                        !text.contains(b),
                        "codename {b:?} leaked into customer string {text:?} for {s:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn no_raw_tier_words_in_customer_copy() {
        for s in CustomerState::all() {
            for b in ["DENY", "WARN", "ALLOW"] {
                assert!(!s.copy().contains(b), "raw tier word {b} in copy for {s:?}");
                assert!(!s.label().contains(b), "raw tier word {b} in label for {s:?}");
            }
        }
    }

    #[test]
    fn every_state_has_complete_token_set() {
        for s in CustomerState::all() {
            assert!(!s.as_str().is_empty());
            assert!(!s.label().is_empty());
            assert!(!s.copy().is_empty());
            assert!(s.color_token().starts_with("--cl-"));
            assert!(s.color_hex().starts_with('#') && s.color_hex().len() == 7);
            assert!(!s.emoji().is_empty());
        }
    }

    #[test]
    fn clean_uses_brand_cyan_others_do_not() {
        assert_eq!(CustomerState::Clean.color_hex(), "#50C0E0");
        for s in CustomerState::all() {
            if s != CustomerState::Clean {
                assert_ne!(s.color_hex(), "#50C0E0", "{s:?} must not reuse brand cyan");
            }
        }
    }

    #[test]
    fn needs_input_family_is_exactly_not_yet_assessed_and_range_not_resolved() {
        // The needs-input predicate is the single source of truth for "not a
        // finding, needs customer input". It must cover exactly the two states
        // that share the `--cl-unknown` token + `❔` glyph — no more, no less.
        // A future state added to this family updates this test + the predicate
        // together; a finding state accidentally landing here fails loudly.
        for s in CustomerState::all() {
            let expected = matches!(
                s,
                CustomerState::NotYetAssessed | CustomerState::RangeNotResolved
            );
            assert_eq!(s.is_needs_input(), expected, "{s:?}");
            if s.is_needs_input() {
                // Needs-input states are warn-tier (never block/clean) and carry
                // the shared unknown visual family — the invariant the LSP and
                // other surfaces rely on.
                assert_eq!(s.tier(), Tier::Warn, "{s:?} needs-input must be warn-tier");
                assert_eq!(s.color_token(), "--cl-unknown", "{s:?}");
                assert_eq!(s.emoji(), "", "{s:?}");
            }
        }
    }

    #[test]
    fn machine_strings_are_unique() {
        let mut seen = std::collections::HashSet::new();
        for s in CustomerState::all() {
            assert!(seen.insert(s.as_str()), "duplicate state string {}", s.as_str());
        }
    }
    #[test]
    fn cleanlib_657_cx8_only_clean_is_allowed_tier() {
        // CX-8 type invariant: `Clean` is the ONLY state at the allowed (Clean)
        // tier. Every other state — crucially NotYetAssessed and RangeNotResolved
        // (the "we did not / could not assess" states) — is Warn or Block tier,
        // so a caller can NEVER accidentally treat "not assessed" as allowed.
        // [Absence≠safe] enforced by the type, not by convention.
        use CustomerState::*;
        let all = [
            BlockedByPolicy, Compromised, Malicious, RansomwareLinked,
            ActivelyExploited, Vulnerable, RangeNotResolved, NotYetAssessed, Clean,
        ];
        for s in all {
            if matches!(s, Clean) {
                assert_eq!(s.tier(), Tier::Clean, "Clean must be allowed-tier");
            } else {
                assert_ne!(s.tier(), Tier::Clean, "{s:?} must NEVER be allowed (Clean) tier");
            }
        }
    }

    // ─── CLEANLIB-855: from_block_origin finally has a real call path ────────

    #[test]
    fn cleanlib_855_is_curated_supply_chain_compromise_matches_the_real_bridge_prefix() {
        assert!(is_curated_supply_chain_compromise(Some(
            "supply-chain-compromise-bridge-event-stream-2018-mh6f-8j2x-4483"
        )));
        assert!(is_curated_supply_chain_compromise(Some(
            "supply-chain-compromise-bridge-ctx-2022-67r3-h899-9w95-compromised"
        )));
        // An ordinary customer policy rule is NOT a curated compromise match,
        // even if it happens to deny the same package.
        assert!(!is_curated_supply_chain_compromise(Some("rule_cors_deny_old")));
        assert!(!is_curated_supply_chain_compromise(None));
        assert!(!is_curated_supply_chain_compromise(Some("")));
    }

    #[test]
    fn cleanlib_855_from_wire_with_source_state_and_origin_renders_compromised() {
        // The exact counterexample the ticket asks for: a curated bridge rule
        // match must render Compromised, not the generic BlockedByPolicy.
        let state = CustomerState::from_wire_with_source_state_and_origin(
            "DM_THRESHOLD_BLOCK",
            None,
            Some("supply-chain-compromise-bridge-event-stream-2018-mh6f-8j2x-4483"),
        );
        assert_eq!(state, CustomerState::Compromised);
        assert_eq!(state.label(), "Compromised");
    }

    #[test]
    fn cleanlib_855_from_wire_with_source_state_and_origin_ordinary_policy_denies_unaffected() {
        // Counterexample's other pole: an ordinary customer DENY rule must
        // still render BlockedByPolicy, not spuriously become Compromised.
        let state = CustomerState::from_wire_with_source_state_and_origin(
            "DM_THRESHOLD_BLOCK",
            None,
            Some("rule_cors_deny_old"),
        );
        assert_eq!(state, CustomerState::BlockedByPolicy);
    }

    #[test]
    fn cleanlib_855_from_wire_with_source_state_and_origin_none_matches_plain_from_wire() {
        // No matched_rule_id at all (pre-855 App, or a non-policy source) must
        // behave IDENTICALLY to the pre-855 from_wire_with_source_state --
        // this is the byte-identical-on-the-common-path guarantee.
        for src in ALL_VERDICT_SOURCES {
            assert_eq!(
                CustomerState::from_wire_with_source_state_and_origin(src, None, None),
                CustomerState::from_wire_with_source_state(src, None),
                "no matched_rule_id must never change behavior for source {src}"
            );
        }
    }

    #[test]
    fn cleanlib_855_curated_compromise_never_fires_on_a_non_block_source() {
        // A curated-looking rule id paired with a NON-DM_THRESHOLD_BLOCK
        // source (shouldn't happen in practice, but defensive) must not
        // spuriously produce Compromised -- from_block_origin only
        // special-cases the exact ("DM_THRESHOLD_BLOCK", true) pair.
        let state = CustomerState::from_wire_with_source_state_and_origin(
            "CVE_FINDING",
            None,
            Some("supply-chain-compromise-bridge-whatever"),
        );
        assert_eq!(state, CustomerState::Vulnerable);
    }

    #[test]
    fn cleanlib_855_source_state_takes_precedence_over_source_for_origin_resolution() {
        // Mirrors from_wire_with_source_state's own precedence: when
        // source_state is present and non-empty, it -- not the legacy
        // `source` -- is what the block-origin override resolves against.
        let state = CustomerState::from_wire_with_source_state_and_origin(
            "VECTOR_VERDICT", // legacy source, would NOT match DM_THRESHOLD_BLOCK
            Some("DM_THRESHOLD_BLOCK"),
            Some("supply-chain-compromise-bridge-event-stream-2018-mh6f-8j2x-4483"),
        );
        assert_eq!(state, CustomerState::Compromised);
    }
}