cleanlib-client 0.1.8

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
//! `verdict_to_envelope_v1` — structural adapter from the App's wire-shape
//! `Verdict` to the canonical customer-facing [`VerdictEnvelopeV1`].
//!
//! Ratified at `decisions/2026-06-05-cycle-14-cleanlib-48-envelope-shape-ratification.md`.
//! Sister of:
//! - `cleanlib_sdk.verdict_to_envelope_v1` (sdk-py, planned)
//! - `verdictToEnvelopeV1` (sdk-js, planned)
//! - `VerdictToEnvelopeV1` (sdk-go, planned)
//!
//! ## Algorithm
//!
//! The adapter is a PURE STRUCTURAL CONVERSION — it does not call the
//! enrich-customer cascade. The output envelope's `remediation` /
//! `exploitability` / `availability` slots are always `None`; consumers
//! populate them via [`crate::HttpEnrichClient`]-equivalent calls before
//! running [`crate::derive_status`] for canonical decision derivation.
//!
//! Field mapping:
//!
//! | Envelope field | Source on `Verdict` |
//! |---|---|
//! | `status` | derived from `verdict.verdict` (label) + `verdict.severity` per the table below |
//! | `reason_code` | derived from `verdict.verdict` + `verdict.severity` per the table below |
//! | `human_message` | `verdict.reasoning` (passthrough) |
//! | `as_of` | `verdict.computed_at` if present, else `verdict.data_freshness_at`, else `""` |
//! | `rich_data` | JSON object built from the legacy Verdict's rich-data fields + suggested_actions/similar_to/evidence_gaps/previous_verdict |
//! | `remediation` | `None` (filled by enrich cascade) |
//! | `exploitability` | `None` (filled by enrich cascade) |
//! | `availability` | `None` (filled by enrich cascade) |
//!
//! Status/reason_code mapping table (App's view; consumer may re-derive
//! after enriching):
//!
//! | verdict label | severity | status | reason_code |
//! |---|---|---|---|
//! | `VECTOR_VERDICT` | `CRITICAL` | DENY | VERDICT_EXPLOITATION_CRITICAL |
//! | `VECTOR_VERDICT` | `HIGH` | DENY | VERDICT_LOW_TRUST |
//! | `VECTOR_VERDICT` | `MEDIUM` | WARN | VERDICT_ABANDONED |
//! | `VECTOR_VERDICT` | `LOW` / `NONE` | ALLOW | VERDICT_CLEAN |
//! | `DM_THRESHOLD_BLOCK` | `HIGH` / `CRITICAL` | DENY | VERDICT_DENY_LIST |
//! | `DM_THRESHOLD_BLOCK` | `MEDIUM` | WARN | VERDICT_DENY_LIST |
//! | `DM_THRESHOLD_BLOCK` | `LOW` / `NONE` | ALLOW | VERDICT_CLEAN |
//! | `ALLOWED_NO_FINDINGS` | any | ALLOW | VERDICT_CLEAN |
//! | `INSUFFICIENT_DATA` | any | WARN | VERDICT_NOT_YET_ASSESSED | (D1/S1: fail-closed)
//! | (unknown label) | any | ALLOW | VERDICT_CLEAN |
//!
//! Freshness handling: if `verdict.stale_since_at` is `Some(_)`, the
//! reason_code is overridden to `VERDICT_DEGRADED_STALE` (status tier
//! preserved). This is the App's view of staleness — distinct from the
//! enrich-substrate `availability == "degraded_stale"` path that
//! [`crate::derive_status`] applies after the enrich cascade lands.
//!
//! Customers who want the canonical (status, reason_code) derived from
//! BOTH the App's verdict AND the enrich cascade should:
//!
//! ```rust,ignore
//! let verdict = client.fetch_verdict(eco, pkg, ver).await?;
//! let mut envelope = verdict_to_envelope_v1(&verdict);
//! envelope.remediation = enrich_client.get_remediation(eco, pkg).await.ok();
//! envelope.exploitability = enrich_client.get_exploitability(eco, pkg, ver).await.ok();
//! let derived = derive_status(&envelope);
//! ```

use serde_json::{json, Map, Value};

use crate::envelope::{ReasonCode, Status, VerdictEnvelopeV1};
use crate::types::Verdict;

/// Pure-function structural conversion: `Verdict` (App wire shape) →
/// [`VerdictEnvelopeV1`] (canonical customer-facing shape). See module
/// docs for the field-mapping + status/reason_code derivation table.
///
/// Enrich-cascade fields (`remediation`, `exploitability`, `availability`)
/// are always `None`; consumers populate them before calling
/// [`crate::derive_status`] for the canonical decision.
pub fn verdict_to_envelope_v1(verdict: &Verdict) -> VerdictEnvelopeV1 {
    let (status, reason_code) = derive_initial_status_reason(verdict);

    let as_of = verdict
        .computed_at
        .clone()
        .or_else(|| verdict.data_freshness_at.clone())
        .unwrap_or_default();

    let rich_data = build_rich_data(verdict);

    // Cycle-15 observability: passthrough App-emitted `availability` block.
    // CLEANLIB-104 M3: `verdict.availability` is non-Optional; envelope
    // field is also non-Optional `serde_json::Value`. Default-block
    // (degraded_stale=false + all sub-fields None) passes through as
    // `Value::Null` so the envelope's `skip_serializing_if = Value::is_null`
    // omits the key — this preserves byte-identity with the pre-M3 wire.
    // Populated blocks (degraded_stale=true OR any sub-field populated)
    // serialize as an object. CLEANLIB-105 App-3.2 M1/M2: the object may
    // now carry `kev` / `epss` / `exploitation_fusion` string tags whose
    // values `derive_status.rs` reads directly (`"available"` /
    // `"degraded_stale"` etc.).
    let availability_value = if verdict.availability == crate::types::AvailabilityBlock::default() {
        serde_json::Value::Null
    } else {
        let mut obj = Map::new();
        // Only emit the boolean when true — preserves byte-identity with
        // the M0 wire for the 8 pre-existing D.1 goldens (which have
        // {degraded_stale: true}; the JSON object shape is unchanged when
        // no sub-fields are populated).
        if verdict.availability.degraded_stale {
            obj.insert("degraded_stale".to_string(), json!(true));
        }
        if let Some(v) = &verdict.availability.kev {
            obj.insert("kev".to_string(), json!(v));
        }
        if let Some(v) = &verdict.availability.epss {
            obj.insert("epss".to_string(), json!(v));
        }
        if let Some(v) = &verdict.availability.exploitation_fusion {
            obj.insert("exploitation_fusion".to_string(), json!(v));
        }
        Value::Object(obj)
    };

    VerdictEnvelopeV1 {
        status: status.as_str().to_string(),
        reason_code: reason_code.as_str().to_string(),
        human_message: verdict.reasoning.clone(),
        as_of,
        rich_data: Some(rich_data),
        remediation: None,
        exploitability: None,
        availability: availability_value,
    }
}

fn derive_initial_status_reason(verdict: &Verdict) -> (Status, ReasonCode) {
    // Normalize the strings to upper-case so case-skew on the wire doesn't
    // misclassify (cleanlib-core::Severity serializes as upper-case enum
    // names; the SDK Verdict type carries Option<String> so we tolerate
    // legacy lower-case fixtures too).
    let label = verdict.verdict.to_ascii_uppercase();
    let severity = verdict
        .severity
        .as_deref()
        .unwrap_or("NONE")
        .to_ascii_uppercase();

    let (status, reason) = match (label.as_str(), severity.as_str()) {
        ("VECTOR_VERDICT", "CRITICAL") => (Status::Deny, ReasonCode::VerdictExploitationCritical),
        ("VECTOR_VERDICT", "HIGH") => (Status::Deny, ReasonCode::VerdictLowTrust),
        ("VECTOR_VERDICT", "MEDIUM") => (Status::Warn, ReasonCode::VerdictAbandoned),
        ("VECTOR_VERDICT", _) => (Status::Allow, ReasonCode::VerdictClean),
        ("DM_THRESHOLD_BLOCK", "CRITICAL" | "HIGH") => {
            (Status::Deny, ReasonCode::VerdictDenyList)
        }
        ("DM_THRESHOLD_BLOCK", "MEDIUM") => (Status::Warn, ReasonCode::VerdictDenyList),
        ("DM_THRESHOLD_BLOCK", _) => (Status::Allow, ReasonCode::VerdictClean),
        // CLEANLIB-495 (D1) + S1 (cycle-22): not-yet-assessed fails CLOSED to
        // WARN, and now carries the canonical VERDICT_NOT_YET_ASSESSED reason.
        // customer_state maps INSUFFICIENT_DATA → NOT_YET_ASSESSED (warn/exit-2).
        // S1 (PM 731999 §1) added the 18th registry code, retiring the cycle-21
        // VERDICT_CLEAN placeholder (status-correct but reason-incoherent,
        // Discipline #60). Byte-identical to sdk-py/js/go. Triple:
        // (INSUFFICIENT_DATA, WARN, VERDICT_NOT_YET_ASSESSED).
        ("INSUFFICIENT_DATA", _) => (Status::Warn, ReasonCode::VerdictNotYetAssessed),
        // ALLOWED_NO_FINDINGS / unknown → ALLOW + CLEAN (forward-compat).
        _ => (Status::Allow, ReasonCode::VerdictClean),
    };

    // CLEANLIB-176 source-aware reason_code refinement. The label stays
    // VECTOR_VERDICT for all four projection variants (so the status tier above
    // is preserved — existing Status resolution is untouched), but the
    // `verdict.source` field carries the semantic differentiation. Refine the
    // reason_code so customers reading reason_code (not just rich_data.source)
    // can separate KEV / ransomware / malicious from a plain CVE finding.
    // Same override shape as the staleness rule below: status tier preserved,
    // reason_code rewritten. Precedence malicious > ransomware > KEV (mirrors
    // the App-side ransomware > KEV synth ordering; ransomware-vs-KEV ordering
    // is Threat-confirmation-pending — CLEANLIB-176 comment 658233).
    let reason = match verdict.source.to_ascii_uppercase().as_str() {
        "MALICIOUS_TRIAGE" => ReasonCode::VerdictMalicious,
        "CVE_FINDING_ON_RANSOMWARE" => ReasonCode::VerdictRansomwareListed,
        "CVE_FINDING_ON_KEV" => ReasonCode::VerdictKevListed,
        // CVE_FINDING (plain) + the four originals keep the label+severity
        // reason derived above — plain has-CVEs is the upgrade-flow baseline.
        _ => reason,
    };

    // App-side staleness override: if the Verdict says it's stale, surface
    // VERDICT_DEGRADED_STALE while preserving the status tier. Sister of
    // the enrich-substrate freshness override applied by derive_status.
    // Staleness wins over the source refinement — a stale signal is a
    // freshness caveat on whatever the source-refined verdict said.
    if verdict.stale_since_at.is_some() {
        (status, ReasonCode::VerdictDegradedStale)
    } else {
        (status, reason)
    }
}

fn build_rich_data(verdict: &Verdict) -> Value {
    let mut m = Map::new();
    if !verdict.suggested_actions.is_empty() {
        m.insert(
            "suggested_actions".to_string(),
            json!(verdict.suggested_actions),
        );
    }
    if !verdict.similar_to.is_empty() {
        m.insert("similar_to".to_string(), json!(verdict.similar_to));
    }
    if !verdict.evidence_gaps.is_empty() {
        m.insert("evidence_gaps".to_string(), json!(verdict.evidence_gaps));
    }
    if let Some(pv) = &verdict.previous_verdict {
        m.insert(
            "previous_verdict".to_string(),
            json!({
                "verdict_id": pv.verdict_id,
                "verdict": pv.verdict,
                "computed_at": pv.computed_at,
                "diff": pv.diff,
            }),
        );
    }
    // Surface the App-canonical signals customers ask about most often
    // (confidence, composite_score, source, severity) so consumers don't
    // have to keep the original Verdict alongside the envelope.
    m.insert("confidence".to_string(), json!(verdict.confidence));
    m.insert("composite_score".to_string(), json!(verdict.composite_score));
    if !verdict.source.is_empty() {
        m.insert("source".to_string(), json!(verdict.source));
    }
    if let Some(s) = &verdict.severity {
        m.insert("severity".to_string(), json!(s));
    }
    if let Some(s) = &verdict.staleness_reason {
        m.insert("staleness_reason".to_string(), json!(s));
    }
    Value::Object(m)
}

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

    fn allowed_clean_verdict() -> Verdict {
        Verdict {
            verdict_id: "v1".into(),
            verdict: "ALLOWED_NO_FINDINGS".into(),
            source: "ALLOWED_NO_FINDINGS".into(),
            confidence: 0.98,
            composite_score: 12,
            severity: Some("NONE".into()),
            reasoning: "No known CVEs; healthy maintenance signals".into(),
            similar_to: vec![],
            evidence_gaps: vec![],
            suggested_actions: vec![],
            data_freshness_at: Some("2026-05-20T10:00:00Z".into()),
            computed_at: Some("2026-05-20T10:30:00Z".into()),
            ..Default::default()
        }
    }

    fn malware_verdict() -> Verdict {
        Verdict {
            verdict_id: "v2".into(),
            verdict: "VECTOR_VERDICT".into(),
            source: "VECTOR_VERDICT".into(),
            confidence: 0.99,
            composite_score: 92,
            severity: Some("CRITICAL".into()),
            reasoning: "Confirmed malware: bitcoin-wallet credential exfiltration".into(),
            suggested_actions: vec![
                "DENY across all customers".into(),
                "Rotate wallet keys".into(),
            ],
            computed_at: Some("2026-05-20T09:31:00Z".into()),
            ..Default::default()
        }
    }

    #[test]
    fn allowed_no_findings_maps_to_allow_clean() {
        let env = verdict_to_envelope_v1(&allowed_clean_verdict());
        assert_eq!(env.status, "ALLOW");
        assert_eq!(env.reason_code, "VERDICT_CLEAN");
        assert_eq!(env.as_of, "2026-05-20T10:30:00Z");
        assert!(env.human_message.contains("No known CVEs"));
        assert!(env.remediation.is_none());
        assert!(env.exploitability.is_none());
        // CLEANLIB-104 M3: envelope's `availability` is non-Optional
        // (`serde_json::Value`). Adapter emits `Value::Null` when the source
        // Verdict block is default (degraded_stale=false) so the envelope's
        // `skip_serializing_if` omits the key on the wire — byte-identity
        // with the pre-M3 emission preserved.
        assert!(env.availability.is_null());
    }

    #[test]
    fn vector_verdict_critical_maps_to_deny_exploitation_critical() {
        let env = verdict_to_envelope_v1(&malware_verdict());
        assert_eq!(env.status, "DENY");
        assert_eq!(env.reason_code, "VERDICT_EXPLOITATION_CRITICAL");
        let rich = env.rich_data.as_ref().expect("rich_data populated");
        let actions = rich
            .get("suggested_actions")
            .and_then(Value::as_array)
            .expect("suggested_actions in rich_data");
        assert_eq!(actions.len(), 2);
        assert_eq!(rich.get("composite_score"), Some(&json!(92)));
    }

    #[test]
    fn vector_verdict_high_maps_to_deny_low_trust() {
        let mut v = malware_verdict();
        v.severity = Some("HIGH".into());
        let env = verdict_to_envelope_v1(&v);
        assert_eq!(env.status, "DENY");
        assert_eq!(env.reason_code, "VERDICT_LOW_TRUST");
    }

    #[test]
    fn vector_verdict_medium_maps_to_warn_abandoned() {
        let mut v = malware_verdict();
        v.severity = Some("MEDIUM".into());
        let env = verdict_to_envelope_v1(&v);
        assert_eq!(env.status, "WARN");
        assert_eq!(env.reason_code, "VERDICT_ABANDONED");
    }

    #[test]
    fn dm_threshold_block_high_maps_to_deny_deny_list() {
        let mut v = allowed_clean_verdict();
        v.verdict = "DM_THRESHOLD_BLOCK".into();
        v.severity = Some("HIGH".into());
        let env = verdict_to_envelope_v1(&v);
        assert_eq!(env.status, "DENY");
        assert_eq!(env.reason_code, "VERDICT_DENY_LIST");
    }

    #[test]
    fn stale_since_at_overrides_reason_code_to_degraded_stale() {
        let mut v = allowed_clean_verdict();
        v.stale_since_at = Some("2026-04-01T00:00:00Z".into());
        let env = verdict_to_envelope_v1(&v);
        // Status tier preserved (ALLOW for AllowedNoFindings); reason_code
        // overridden to VERDICT_DEGRADED_STALE.
        assert_eq!(env.status, "ALLOW");
        assert_eq!(env.reason_code, "VERDICT_DEGRADED_STALE");
    }

    #[test]
    fn previous_verdict_lands_in_rich_data() {
        let mut v = allowed_clean_verdict();
        v.previous_verdict = Some(PreviousVerdict {
            verdict_id: "vprev".into(),
            verdict: "ALLOWED_NO_FINDINGS".into(),
            computed_at: "2026-04-01T00:00:00Z".into(),
            diff: "verdict_unchanged".into(),
        });
        let env = verdict_to_envelope_v1(&v);
        let rich = env.rich_data.as_ref().expect("rich_data");
        let pv = rich.get("previous_verdict").expect("previous_verdict in rich_data");
        assert_eq!(pv.get("verdict_id").and_then(Value::as_str), Some("vprev"));
    }

    #[test]
    fn as_of_falls_back_to_data_freshness_when_computed_at_absent() {
        let mut v = allowed_clean_verdict();
        v.computed_at = None;
        let env = verdict_to_envelope_v1(&v);
        assert_eq!(env.as_of, "2026-05-20T10:00:00Z");
    }

    #[test]
    fn cleanlib_495_s1_insufficient_data_fails_closed_to_warn_not_yet_assessed() {
        // D1 (CLEANLIB-495) + S1 (cycle-22): INSUFFICIENT_DATA maps to WARN
        // (never silently clean) AND carries the canonical VERDICT_NOT_YET_ASSESSED
        // reason (S1 retired the cycle-21 VERDICT_CLEAN placeholder). The triple
        // (INSUFFICIENT_DATA, WARN, VERDICT_NOT_YET_ASSESSED) is byte-identical to
        // sdk-py/js/go. Distinct from the unknown-label branch, which stays ALLOW
        // for forward-compat.
        let mut v = allowed_clean_verdict();
        v.verdict = "INSUFFICIENT_DATA".into();
        v.severity = Some("NONE".into());
        let env = verdict_to_envelope_v1(&v);
        assert_eq!(env.status, "WARN", "INSUFFICIENT_DATA must fail closed to WARN");
        assert_eq!(env.reason_code, "VERDICT_NOT_YET_ASSESSED");
    }

    #[test]
    fn unknown_verdict_label_falls_through_to_allow_clean() {
        let mut v = allowed_clean_verdict();
        v.verdict = "FUTURE_NEW_LABEL_X".into();
        v.severity = Some("MEDIUM".into());
        let env = verdict_to_envelope_v1(&v);
        // Forward-compat: unknown labels default to ALLOW+CLEAN so older
        // SDKs don't break when the App adds a new label.
        assert_eq!(env.status, "ALLOW");
        assert_eq!(env.reason_code, "VERDICT_CLEAN");
    }

    #[test]
    fn cleanlib_176_source_malicious_triage_refines_reason_to_malicious() {
        // Label stays VECTOR_VERDICT/CRITICAL → status DENY preserved; the
        // MALICIOUS_TRIAGE source refines the reason to VERDICT_MALICIOUS.
        let mut v = malware_verdict();
        v.source = "MALICIOUS_TRIAGE".into();
        let env = verdict_to_envelope_v1(&v);
        assert_eq!(env.status, "DENY");
        assert_eq!(env.reason_code, "VERDICT_MALICIOUS");
    }

    #[test]
    fn cleanlib_176_source_on_kev_refines_reason_to_kev_listed() {
        let mut v = malware_verdict();
        v.source = "CVE_FINDING_ON_KEV".into();
        v.severity = Some("HIGH".into());
        let env = verdict_to_envelope_v1(&v);
        // VECTOR_VERDICT/HIGH → DENY tier preserved; reason refined to KEV.
        assert_eq!(env.status, "DENY");
        assert_eq!(env.reason_code, "VERDICT_KEV_LISTED");
    }

    #[test]
    fn cleanlib_176_source_on_ransomware_refines_reason_to_ransomware_listed() {
        let mut v = malware_verdict();
        v.source = "CVE_FINDING_ON_RANSOMWARE".into();
        let env = verdict_to_envelope_v1(&v);
        assert_eq!(env.reason_code, "VERDICT_RANSOMWARE_LISTED");
    }

    #[test]
    fn cleanlib_176_plain_cve_finding_keeps_severity_driven_reason() {
        // Plain CVE_FINDING (has-CVEs upgrade baseline) is NOT refined — it
        // keeps the label+severity reason (VECTOR_VERDICT/HIGH → LOW_TRUST).
        let mut v = malware_verdict();
        v.source = "CVE_FINDING".into();
        v.severity = Some("HIGH".into());
        let env = verdict_to_envelope_v1(&v);
        assert_eq!(env.status, "DENY");
        assert_eq!(env.reason_code, "VERDICT_LOW_TRUST");
    }

    /// CLEANLIB-48 §4 / PM 729055 §1 (D2 status-authority) — the *SDK* half of the
    /// ratified SDK-vs-wire divergence. The authoritative customer status is
    /// derived here from `label + severity`: a CVE finding (emitted with label
    /// `VECTOR_VERDICT`, source `CVE_FINDING`) at `HIGH` severity is **DENY**. The
    /// severity-blind wire `state` — `cleanlib_core::VerdictSource::CveFinding
    /// .coarse_state()` — is **WARN** (pinned by `coarse_state_is_severity_blind_
    /// wire_hint` in cleanlib-core; not asserted here because cleanlib-client
    /// intentionally carries no cleanlib-core dependency). Where they disagree, the
    /// SDK-derived status wins for customer-facing decisions. This guards against a
    /// regression that would silently collapse the SDK status back to the wire hint.
    #[test]
    fn high_severity_cve_diverges_from_wire_coarse_state() {
        let mut v = malware_verdict(); // label VECTOR_VERDICT — how the App emits a CVE finding
        v.source = "CVE_FINDING".into();
        v.severity = Some("HIGH".into());
        let env = verdict_to_envelope_v1(&v);
        // SDK-authoritative status is DENY (label+severity aware)...
        assert_eq!(env.status, "DENY");
        // ...strictly higher than the severity-blind wire hint "WARN" that
        // cleanlib-core's coarse_state(CveFinding) emits. Divergence is expected
        // and ratified; the SDK status governs the customer-facing decision.
        assert_ne!(env.status, "WARN", "SDK status must not collapse to the wire display hint");
    }

    #[test]
    fn cleanlib_176_staleness_wins_over_source_refinement() {
        // A stale signal is a freshness caveat over whatever the source said —
        // VERDICT_DEGRADED_STALE overrides even MALICIOUS_TRIAGE, tier preserved.
        let mut v = malware_verdict();
        v.source = "MALICIOUS_TRIAGE".into();
        v.stale_since_at = Some("2026-04-01T00:00:00Z".into());
        let env = verdict_to_envelope_v1(&v);
        assert_eq!(env.status, "DENY");
        assert_eq!(env.reason_code, "VERDICT_DEGRADED_STALE");
    }

    #[test]
    fn round_trip_produces_envelope_that_parses_back_unchanged() {
        // Critical: the produced envelope must serialize then parse back
        // to the same shape — proves we're not producing malformed JSON.
        let env = verdict_to_envelope_v1(&malware_verdict());
        let s = serde_json::to_string(&env).unwrap();
        let back: VerdictEnvelopeV1 = serde_json::from_str(&s).unwrap();
        assert_eq!(back.status, env.status);
        assert_eq!(back.reason_code, env.reason_code);
        assert_eq!(back.human_message, env.human_message);
        assert_eq!(back.as_of, env.as_of);
    }

    // ─── CLEANLIB-105 App-3.2 — availability sub-fields on the envelope wire ──

    #[test]
    fn cleanlib_105_availability_sub_fields_appear_on_envelope_when_populated() {
        // A verdict carrying populated sub-field tags emits an availability
        // JSON object with each populated tag as a snake_case string —
        // matches what derive_status.rs reads directly (lines 71, 76+).
        let mut v = allowed_clean_verdict();
        v.availability = crate::types::AvailabilityBlock {
            degraded_stale: true,
            kev: Some("available".to_string()),
            epss: Some("available".to_string()),
            exploitation_fusion: Some("available".to_string()),
        };
        let env = verdict_to_envelope_v1(&v);
        // Envelope.availability is a Value; sub-fields present.
        assert_eq!(env.availability["degraded_stale"], Value::Bool(true));
        assert_eq!(env.availability["kev"], Value::String("available".to_string()));
        assert_eq!(env.availability["epss"], Value::String("available".to_string()));
        assert_eq!(env.availability["exploitation_fusion"], Value::String("available".to_string()));
    }

    #[test]
    fn cleanlib_105_default_availability_still_omits_key_on_wire() {
        // Byte-identity: a default block (degraded_stale=false + no sub-fields)
        // must still emit as Value::Null so the envelope's skip_serializing_if
        // omits the `availability` key entirely from the JSON wire.
        let v = allowed_clean_verdict();
        let env = verdict_to_envelope_v1(&v);
        assert!(env.availability.is_null());
        // And that omission survives serialize→wire.
        let s = serde_json::to_string(&env).unwrap();
        assert!(!s.contains("\"availability\""));
    }

    #[test]
    fn cleanlib_105_degraded_stale_only_matches_pre_m1_wire_shape() {
        // The 8 pre-existing D.1 goldens carry `{"degraded_stale": true}`
        // as the availability object. That exact shape must still emit
        // when sub-fields are None — byte-identity preserved.
        let mut v = allowed_clean_verdict();
        v.availability = crate::types::AvailabilityBlock {
            degraded_stale: true,
            kev: None,
            epss: None,
            exploitation_fusion: None,
        };
        let env = verdict_to_envelope_v1(&v);
        assert_eq!(
            env.availability,
            serde_json::json!({"degraded_stale": true})
        );
    }

    #[test]
    fn cleanlib_105_kev_only_populated_still_emits_object() {
        // Happy-path Vector verdict with only kev populated (no degraded_stale,
        // no epss) emits a lean object `{"kev": "available"}`. This is the M2
        // shape for a Tricorder-answered clean verdict on a CVE-less package.
        let mut v = allowed_clean_verdict();
        v.availability = crate::types::AvailabilityBlock {
            degraded_stale: false,
            kev: Some("available".to_string()),
            epss: None,
            exploitation_fusion: None,
        };
        let env = verdict_to_envelope_v1(&v);
        assert_eq!(
            env.availability,
            serde_json::json!({"kev": "available"})
        );
    }
}