cleanlib-cli 0.1.5

Terminal interface to CleanLibrary — query dependency verdicts and scan package manifests for ALLOW / DENY / WARN signals from the terminal or CI pipelines.
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
//! JSON renderer for `cleanlib verdict --output json`.
//!
//! CLEANLIB-165 root cause: the old code did
//! `serde_json::to_string_pretty(verdict)` directly, serialising the raw
//! [`cleanlib_client::types::Verdict`] struct. That struct carries
//! `decision: Option<String>` as a serde-default-tolerant field (added in
//! cycle-9 Lane-2 M1 to survive pre-R1 payloads that omit the key). When
//! the server returns a pre-R1 envelope, `decision` deserialises to `None`
//! and the JSON output shows `"decision": null`, even though the text renderer
//! correctly derived the tier from the `verdict` label.
//!
//! Fix: introduce [`VerdictResponse`] as a stable serialisation shape.
//! `decision` is always computed from [`super::output::decision_tier_str`]
//! (same logic the text renderer uses), so it is never null. Engine tags and
//! fixture labels are masked before serialisation so internal routing details
//! are not exposed to callers.

use serde::{Deserialize, Serialize};
use cleanlib_client::types::{Verdict,PreviousVerdict,AvailabilityBlock};
use cleanlib_client::CustomerState;
use super::sanitize::{mask_engine_tag, mask_fixture_label};
use super::output::decision_tier_str_with_severity;

/// Placeholder: Controls rendering behaviour passed to every entry-point in this module.
#[derive(Debug, Clone, Copy,Default)]
#[allow(dead_code)]
pub struct RenderOpts {
}

/// Stable JSON serialisation envelope for a verdict result.
///
/// Exists instead of serialising [`Verdict`] directly for two reasons:
/// 1. `Verdict::decision` is `Option<String>` for serde-default tolerance and
///    is `None` on pre-R1 server payloads — see the module-level note on
///    CLEANLIB-165.
/// 2. `verdict` and `source` are masked here; the raw SDK type carries
///    unmasked engine tags.
///
/// Optional fields use `skip_serializing_if = "Option::is_none"` so absent
/// values are omitted from the JSON output rather than appearing as `null`.
/// Exception: `previous_verdict` and `availability` deliberately allow `null`
/// to match the App's canonical envelope shape (see [`Verdict`] doc).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerdictResponse {
    pub verdict_id: String,
    pub verdict: String,
    /// Masked source label — fixture prefixes and engine tags are stripped.
    pub source: String,
    pub confidence: f64,
    pub composite_score: u8,

    /// **DEPRECATED (CLEANLIB-496B, BD-ratified option B @ 0.1.5)** — will be
    /// removed in 0.2.0. Use `state` / `state_label` (below) + the process exit
    /// code instead. `decision` was a CLI-local shadow of the wire-authoritative
    /// status (discipline #55 vocab breach); it is retained here only for one
    /// deprecation window so customers scripting on `jq .decision` are not
    /// hard-broken in a pre-1.0 minor bump (0.1.4→0.1.5 is semver-compatible per
    /// cargo). NOT authoritative — `state`/`state_label` are. A one-line stderr
    /// deprecation notice fires on json/sarif render (see `render_verdict`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decision: Option<String>,

    /// CLEANLIB-371 (cycle-18) — canonical customer-facing state, snake_case
    /// machine string. Derived via `CustomerState::from_wire(source)` so JSON
    /// consumers get the same 8-state taxonomy the text renderer emits in its
    /// header line + the SDKs / MCP mirror. Values: `blocked_by_policy`,
    /// `compromised`, `malicious`, `ransomware_linked`, `actively_exploited`,
    /// `vulnerable`, `not_yet_assessed`, `clean`. Always present.
    pub state: String,

    /// CLEANLIB-371 (cycle-18) — canonical human-readable state label
    /// (`CustomerState::label()`). The `verdict` field can carry the wire
    /// label (or its masked form); `state_label` is the single stable string
    /// customer-facing tools should surface for the "8 states" taxonomy.
    pub state_label: String,

    pub reasoning: String,

    /// IDs of similar verdicts; omitted when empty to avoid noise.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub similar_to: Option<Vec<String>>,
    pub evidence_gaps: Vec<String>,
    pub suggested_actions: Vec<String>,
    pub severity: Option<String>,

    pub data_freshness_at: Option<String>,
    pub data_oldest_signal_at: Option<String>,

    /// Set when the underlying signal data became stale; omitted if fresh.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stale_since_at: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub staleness_reason: Option<String>,

    pub computed_at: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub previous_verdict: Option<PreviousVerdict>,

    /// CLEANLIB-104 App-3.1 Gate M3: non-Optional per the design doc.
    /// `skip_serializing_if = "AvailabilityBlock::is_default"` preserves
    /// the byte-identity omission on happy-path verdicts (a default block
    /// serialized the same as pre-M3's `availability: None`).
    #[serde(default, skip_serializing_if = "availability_block_is_default")]
    pub availability: AvailabilityBlock,

    // ─── CLEANLIB-496 (C1) — machine-readable attestation parity ─────────────
    // Surface the envelope-v2 audit + attestation fields the client already
    // parses but the CLI JSON previously dropped. All `skip_serializing_if
    // None` → v1 / unsigned responses stay byte-identical (omitted, not null).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub envelope_version: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy_version: Option<String>,
    /// FK (ULID) to the frozen WORM audit record (CLEANLIB-A2 wire-receipt).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audit_record_id: Option<String>,
    /// hex SHA-256 tamper-evident binding to the audit record `content_hash`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audit_record_hash: Option<String>,
    /// Signed attestation passthrough `{attestation:{…}, signature_b64, key_id}`
    /// — customers verify signatures on machine-readable output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attestation: Option<serde_json::Value>,
}

/// SDK-side sibling of `cleanlib_core::AvailabilityBlock::is_default`.
/// Kept as a free function because the SDK-mirror `AvailabilityBlock` sits in
/// `cleanlib-client` (external crate to this render module) and cannot carry
/// an inherent impl here. Semantics: a block equal to `Default::default()`
/// omits from the JSON wire — preserving byte-identity with the pre-M3
/// happy-path emission.
fn availability_block_is_default(a: &AvailabilityBlock) -> bool {
    *a == AvailabilityBlock::default()
}

impl From<&Verdict> for VerdictResponse {
    fn from(v: &Verdict) -> Self {
        // CLEANLIB-371 (cycle-18): derive the canonical customer-state from
        // the wire `source`. Sister of the text renderer's
        // `render_customer_state()` — both call `CustomerState::from_wire()`,
        // so JSON + text emit the SAME label for the SAME wire source.
        let state = CustomerState::from_wire(&v.source);
        VerdictResponse {
            verdict_id: v.verdict_id.clone(),
            verdict: mask_engine_tag(&v.verdict),
            source: mask_fixture_label(&mask_engine_tag(&v.source)),
            confidence: v.confidence.clone(),
            composite_score: v.composite_score.clone(),
            // CLEANLIB-496B (deprecated dual-emit): derive from the label (not
            // v.decision, which is None on pre-R1 payloads). Removed in 0.2.0.
            decision: Some(
                decision_tier_str_with_severity(&v.verdict, v.severity.as_deref(), v.composite_score)
                    .to_string(),
            ),
            state: state.as_str().to_string(),
            state_label: state.label().to_string(),

            reasoning: v.reasoning.clone(),
            suggested_actions: v.suggested_actions.clone(),
            // Coerce empty vec → None so the field is omitted, not `[]`.
            similar_to: (!v.similar_to.is_empty()).then(|| v.similar_to.clone()),
            evidence_gaps: v.evidence_gaps.clone(),
            severity: v.severity.clone(),
            data_freshness_at: v.data_freshness_at.clone(),
            data_oldest_signal_at: v.data_oldest_signal_at.clone(),
            stale_since_at: v.stale_since_at.clone(),
            staleness_reason: v.staleness_reason.clone(),
            computed_at: v.computed_at.clone(),
            previous_verdict: v.previous_verdict.clone(),
            // CLEANLIB-104 M3: non-Optional passthrough. Default-block is
            // skipped on serialize via `availability_block_is_default`.
            availability: v.availability.clone(),
            // CLEANLIB-496 (C1): envelope-v2 audit + attestation passthrough.
            envelope_version: v.envelope_version,
            policy_version: v.policy_version.clone(),
            audit_record_id: v.audit_record_id.clone(),
            audit_record_hash: v.audit_record_hash.clone(),
            attestation: v.attestation.clone(),
        }
    }
}

/// Severity tiers carried on the verdict envelope.
/// Serialised as `SCREAMING_SNAKE_CASE` to match the App wire contract.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Severity {
    Low,
    Medium,
    High,
    Critical,
}

/// Serialise `verdict` as pretty-printed JSON and write it to stdout.
///
/// Serialisation errors are silently discarded; callers that need propagation
/// should build [`VerdictResponse::from`] and call [`serde_json::to_string_pretty`]
/// directly.
pub fn render_verdict(verdict: &Verdict, _opts: &RenderOpts) {
    let response = VerdictResponse::from(verdict);
    let result: Result<String, serde_json::Error> = serde_json::to_string_pretty(&response);
    match result {
        Ok(json) => {
            // CLEANLIB-496B: one-line deprecation notice on stderr (never stdout,
            // so it can't corrupt a `| jq` pipeline). The `decision` field stays
            // emitted for the 0.1.x deprecation window; removed in 0.2.0.
            eprintln!(
                "warning: `decision` in --output json is DEPRECATED and will be removed in 0.2.0; use `state`/`state_label` + the exit code."
            );
            println!("{}", json);
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cleanlib_client::types::{Verdict, PreviousVerdict, AvailabilityBlock};

    fn make_verdict(verdict_label: &str, composite_score: u8) -> Verdict {
        Verdict {
            verdict_id: "vrd-test-001".to_string(),
            verdict: verdict_label.to_string(),
            source: "npm".to_string(),
            confidence: 0.85,
            composite_score,
            reasoning: "Test reasoning.".to_string(),
            similar_to: vec![],
            evidence_gaps: vec![],
            suggested_actions: vec![],
            data_freshness_at: None,
            data_oldest_signal_at: None,
            stale_since_at: None,
            staleness_reason: None,
            computed_at: None,
            severity: None,
            decision: None,
            previous_verdict: None,
            availability: AvailabilityBlock::default(),
            // CLEANLIB-252 follow-up: fill the envelope-v2 fields added to
            // `Verdict` after this helper was written (keeps the literal compiling).
            ..Default::default()
        }
    }

    // ── CLEANLIB-496B (BD-ratified B @ 0.1.5): decision dual-emitted, deprecated ─

    #[test]
    fn cleanlib_496b_decision_dual_emitted_alongside_state() {
        // BD ratified option (B): `decision` is RETAINED (deprecated) for the
        // 0.1.x window — additive, non-breaking — alongside `state`/`state_label`
        // (the authoritative surface). Hard removal deferred to 0.2.0.
        let out = serde_json::to_value(&VerdictResponse::from(&make_verdict("ALLOWED_NO_FINDINGS", 20))).unwrap();
        let obj = out.as_object().unwrap();
        assert!(obj.contains_key("decision"), "deprecated `decision` retained for the 0.1.x window (CLEANLIB-496B option B)");
        assert_eq!(out["decision"], "ALLOW"); // derived from the verdict label, not source
        assert!(obj.contains_key("state"), "authoritative state still present alongside deprecated decision");
        assert!(obj.contains_key("state_label"));
    }

    #[test]
    fn cleanlib_496_attestation_and_audit_fields_surface() {
        // C1: the envelope-v2 audit + signed-attestation payload the client parses
        // is now rendered on --output json (previously dropped).
        let mut v = make_verdict("ALLOWED_NO_FINDINGS", 20);
        v.envelope_version = Some(2);
        v.policy_version = Some("1.1.0".into());
        v.audit_record_id = Some("01KZ9X7C52PSDQD9DKFVCJH2CQ".into());
        v.audit_record_hash = Some("a41d6451384f787b3b0470d80ab6a90decc1dbd81dce60692d13b2018abbc231".into());
        v.attestation = Some(serde_json::json!({
            "attestation": { "served_at": "2026-08-06T00:00:00.000000Z" },
            "signature_b64": "MEUCIQD-signature-bytes",
            "key_id": "cleanlib-cosign-staging",
        }));
        let out = serde_json::to_value(&VerdictResponse::from(&v)).unwrap();
        assert_eq!(out["envelope_version"], 2);
        assert_eq!(out["policy_version"], "1.1.0");
        assert_eq!(out["audit_record_id"], "01KZ9X7C52PSDQD9DKFVCJH2CQ");
        assert_eq!(out["audit_record_hash"], "a41d6451384f787b3b0470d80ab6a90decc1dbd81dce60692d13b2018abbc231");
        // Attestation passthrough — key_id + signature_b64 available for verify.
        assert_eq!(out["attestation"]["key_id"], "cleanlib-cosign-staging");
        assert_eq!(out["attestation"]["signature_b64"], "MEUCIQD-signature-bytes");
    }

    #[test]
    fn cleanlib_496_unsigned_v1_omits_attestation_fields() {
        // v1 / unsigned response → new fields omitted (skip_serializing_if None),
        // preserving byte-identity with the pre-496 wire.
        let out = serde_json::to_value(&VerdictResponse::from(&make_verdict("ALLOWED_NO_FINDINGS", 20))).unwrap();
        let obj = out.as_object().unwrap();
        for k in ["envelope_version", "policy_version", "audit_record_id", "audit_record_hash", "attestation"] {
            assert!(!obj.contains_key(k), "unsigned response must omit `{k}`");
        }
    }

    // ── engine-tag masking on verdict / source ────────────────────────────────

    #[test]
    fn verdict_field_engine_tag_is_masked() {
        let r = VerdictResponse::from(&make_verdict("VECTOR_VERDICT", 85));
        assert_eq!(r.verdict, "Engine signal");
    }

    #[test]
    fn source_with_engine_tag_is_masked() {
        let mut v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        v.source = "VECTOR_VERDICT".to_string();
        let r = VerdictResponse::from(&v);
        assert_eq!(r.source, "Engine signal");
    }

    #[test]
    fn source_with_fixture_prefix_is_hidden() {
        let mut v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        v.source = "mock_npm_fixture".to_string();
        let r = VerdictResponse::from(&v);
        assert_eq!(r.source, "");
    }

    #[test]
    fn customer_facing_source_passes_through() {
        let mut v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        v.source = "Cleanstart-curated catalog".to_string();
        let r = VerdictResponse::from(&v);
        assert_eq!(r.source, "Cleanstart-curated catalog");
    }

    // ── similar_to: empty vec → None ─────────────────────────────────────────

    #[test]
    fn similar_to_empty_coerced_to_none() {
        let mut v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        v.similar_to = vec![];
        let r = VerdictResponse::from(&v);
        assert!(r.similar_to.is_none());
    }

    #[test]
    fn similar_to_nonempty_preserved() {
        let mut v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        v.similar_to = vec!["vrd-abc".to_string(), "vrd-def".to_string()];
        let r = VerdictResponse::from(&v);
        assert_eq!(r.similar_to, Some(vec!["vrd-abc".to_string(), "vrd-def".to_string()]));
    }

    // ── JSON serialisation shape ──────────────────────────────────────────────

    // (CLEANLIB-496B: `decision` is retained-but-DEPRECATED for the 0.1.x window
    // per BD-ratified option B; see cleanlib_496b_decision_dual_emitted_alongside_state.
    // Removed in 0.2.0.)

    #[test]
    fn similar_to_omitted_from_json_when_empty_input() {
        let r = VerdictResponse::from(&make_verdict("ALLOWED_NO_FINDINGS", 30));
        let json = serde_json::to_value(&r).unwrap();
        assert!(json.get("similar_to").is_none(), "similar_to must be absent from JSON when empty");
    }

    #[test]
    fn similar_to_present_in_json_when_nonempty() {
        let mut v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        v.similar_to = vec!["vrd-xyz".to_string()];
        let r = VerdictResponse::from(&v);
        let json = serde_json::to_value(&r).unwrap();
        assert!(json.get("similar_to").is_some());
    }

    #[test]
    fn stale_since_at_omitted_from_json_when_none() {
        let r = VerdictResponse::from(&make_verdict("ALLOWED_NO_FINDINGS", 30));
        let json = serde_json::to_value(&r).unwrap();
        assert!(json.get("stale_since_at").is_none());
    }

    #[test]
    fn stale_since_at_present_in_json_when_set() {
        let mut v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        v.stale_since_at = Some("2026-01-01T00:00:00Z".to_string());
        let r = VerdictResponse::from(&v);
        let json = serde_json::to_value(&r).unwrap();
        assert_eq!(json["stale_since_at"], "2026-01-01T00:00:00Z");
    }

    #[test]
    fn staleness_reason_omitted_from_json_when_none() {
        let r = VerdictResponse::from(&make_verdict("ALLOWED_NO_FINDINGS", 30));
        let json = serde_json::to_value(&r).unwrap();
        assert!(json.get("staleness_reason").is_none());
    }

    #[test]
    fn previous_verdict_omitted_from_json_when_none() {
        let r = VerdictResponse::from(&make_verdict("ALLOWED_NO_FINDINGS", 30));
        let json = serde_json::to_value(&r).unwrap();
        assert!(json.get("previous_verdict").is_none());
    }

    #[test]
    fn previous_verdict_present_in_json_when_set() {
        let mut v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        v.previous_verdict = Some(PreviousVerdict {
            verdict_id: "vrd-prev".to_string(),
            verdict: "ALLOWED_NO_FINDINGS".to_string(),
            computed_at: "2026-01-01T00:00:00Z".to_string(),
            diff: "no change".to_string(),
        });
        let r = VerdictResponse::from(&v);
        let json = serde_json::to_value(&r).unwrap();
        assert_eq!(json["previous_verdict"]["verdict_id"], "vrd-prev");
    }

    #[test]
    fn availability_omitted_from_json_when_default() {
        // CLEANLIB-104 M3: non-Optional wrapper. A default block
        // (degraded_stale=false) skip-serializes → wire-byte-identity with
        // the pre-M3 `availability: None` omission preserved.
        let r = VerdictResponse::from(&make_verdict("ALLOWED_NO_FINDINGS", 30));
        let json = serde_json::to_value(&r).unwrap();
        assert!(json.get("availability").is_none());
    }

    #[test]
    fn availability_present_in_json_when_set() {
        // CLEANLIB-104 M3: populated block (degraded_stale=true) still
        // serializes as a JSON object exactly as pre-M3 —
        // `Some(AvailabilityBlock { degraded_stale: true })`  is
        // byte-identical to `AvailabilityBlock { degraded_stale: true }` on
        // the wire.
        let mut v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        v.availability = AvailabilityBlock {
            degraded_stale: true,
            ..AvailabilityBlock::default()
        };
        let r = VerdictResponse::from(&v);
        let json = serde_json::to_value(&r).unwrap();
        assert_eq!(json["availability"]["degraded_stale"], true);
    }

    #[test]
    fn availability_default_deserialize_on_missing_key() {
        // CLEANLIB-104 M3 fail-open: a JSON payload without the
        // `availability` key deserializes into `AvailabilityBlock::default()`
        // (degraded_stale=false). No wire-shape crash on pre-M3 payloads
        // arriving at an M3 reader.
        let raw = r#"{
            "verdict_id":"vrd-test-noavail",
            "verdict":"ALLOWED_NO_FINDINGS",
            "source":"npm",
            "confidence":1.0,
            "composite_score":0,
            "reasoning":"no block on wire",
            "similar_to":[],
            "evidence_gaps":[],
            "suggested_actions":[],
            "data_freshness_at":null,
            "data_oldest_signal_at":null,
            "stale_since_at":null,
            "staleness_reason":null,
            "computed_at":null,
            "severity":null,
            "decision":null,
            "previous_verdict":null
        }"#;
        let v: Verdict = serde_json::from_str(raw).expect("deserialize succeeds");
        assert_eq!(v.availability, AvailabilityBlock::default());
        assert_eq!(v.availability.degraded_stale, false);
    }

    // ── scalar field pass-through ─────────────────────────────────────────────

    #[test]
    fn scalar_fields_pass_through_unchanged() {
        let v = make_verdict("ALLOWED_NO_FINDINGS", 42);
        let r = VerdictResponse::from(&v);
        assert_eq!(r.verdict_id, "vrd-test-001");
        assert_eq!(r.confidence, 0.85);
        assert_eq!(r.composite_score, 42);
        assert_eq!(r.reasoning, "Test reasoning.");
    }

    // ── CLEANLIB-371 (cycle-18) — canonical state field ──────────────────────
    //
    // The JSON output surface used to leak raw wire codenames in `verdict`
    // (e.g. `verdict: "INSUFFICIENT_DATA"`) and never emitted a customer-facing
    // state at all — customers pointing 3 different tools (CLI text, CLI JSON,
    // SDK) at the same package got 3 different labels. These tests pin the
    // wire shape so `state` + `state_label` are always present + canonical.

    fn make_verdict_with_source(source: &str, verdict_label: &str) -> Verdict {
        let mut v = make_verdict(verdict_label, 30);
        v.source = source.to_string();
        v
    }

    #[test]
    fn state_field_derived_from_wire_source_insufficient_data() {
        let r = VerdictResponse::from(&make_verdict_with_source(
            "INSUFFICIENT_DATA",
            "INSUFFICIENT_DATA",
        ));
        assert_eq!(r.state, "not_yet_assessed");
        assert_eq!(r.state_label, "Not yet assessed");
    }

    #[test]
    fn state_field_derived_from_wire_source_clean() {
        let r = VerdictResponse::from(&make_verdict_with_source(
            "ALLOWED_NO_FINDINGS",
            "ALLOWED_NO_FINDINGS",
        ));
        assert_eq!(r.state, "clean");
        assert_eq!(r.state_label, "Clean");
    }

    #[test]
    fn state_field_derived_from_wire_source_vulnerable() {
        let r = VerdictResponse::from(&make_verdict_with_source("CVE_FINDING", "VECTOR_VERDICT"));
        assert_eq!(r.state, "vulnerable");
        assert_eq!(r.state_label, "Vulnerable");
    }

    #[test]
    fn state_field_derived_from_wire_source_actively_exploited() {
        let r = VerdictResponse::from(&make_verdict_with_source(
            "CVE_FINDING_ON_KEV",
            "VECTOR_VERDICT",
        ));
        assert_eq!(r.state, "actively_exploited");
        assert_eq!(r.state_label, "Actively exploited");
    }

    #[test]
    fn state_field_fails_closed_to_not_yet_assessed_on_unknown_wire_source() {
        // Anti-drift: an unknown / future wire source must NEVER silently
        // map to `clean`. `CustomerState::from_wire` fails CLOSED to
        // `NotYetAssessed`; the JSON surface inherits that guarantee.
        let r = VerdictResponse::from(&make_verdict_with_source(
            "SOME_FUTURE_WIRE_TAG",
            "SOME_FUTURE_WIRE_TAG",
        ));
        assert_eq!(r.state, "not_yet_assessed");
        assert_ne!(r.state, "clean");
    }

    #[test]
    fn state_field_always_present_in_json_output() {
        // Wire-contract: `state` + `state_label` are non-Option and must
        // ALWAYS serialise. A downstream tool keying off these must never
        // see them absent.
        let r = VerdictResponse::from(&make_verdict("ALLOWED_NO_FINDINGS", 30));
        let json = serde_json::to_value(&r).unwrap();
        assert!(json.get("state").is_some(), "state key must be present");
        assert!(!json["state"].is_null(), "state must not be null");
        assert!(
            json.get("state_label").is_some(),
            "state_label key must be present"
        );
        assert!(
            !json["state_label"].is_null(),
            "state_label must not be null"
        );
    }

    #[test]
    fn verdict_field_no_longer_leaks_insufficient_data_codename() {
        // CLEANLIB-371 — the CLI JSON surface used to emit
        // `verdict: "INSUFFICIENT_DATA"` verbatim, leaking the raw wire
        // codename onto every downstream JSON consumer. The masker now
        // canonicalises to "Not yet assessed" so text/JSON/SARIF agree.
        let r = VerdictResponse::from(&make_verdict("INSUFFICIENT_DATA", 30));
        assert!(
            !r.verdict.contains("INSUFFICIENT_DATA"),
            "raw wire codename leaked in verdict field: {}",
            r.verdict
        );
        assert_eq!(r.verdict, "Not yet assessed");
    }
}