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
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
//! Verdict + ancillary response types per Client spec rev1 §2.4 +
//! App Rev 4 §4.1 Vector verdict shape.
//!
//! All fields default-tolerant via `#[serde(default)]` so the SDK can
//! consume partial responses during cycle-3 → cycle-N spec evolution
//! without forcing a recompile-and-redeploy on every App-side schema
//! widening.

use serde::{Deserialize, Serialize};

/// `Verdict` mirrors App Rev 4 §4.1 `Verdict` struct surfaced via
/// `GET /v1/customer/verdicts/{ecosystem}/{package}/{version}`.
///
/// Cycle-9 R1 fix-forward Lane-2 M1: adds `severity` + `decision` to align
/// with the App-canonical envelope shape (sister of `cleanlib-core::Verdict`
/// + js/py/go SDK envelope carrying). All new fields are `Option<String>`
/// to preserve serde-default tolerance — pre-R1 verdict payloads (without
/// these fields) deserialize cleanly with `None`. Sister-shape with the
/// `VerdictEnvelopeV1` schema-locked at `cleanlib-contract-fixtures@v1.0.0`.
/// CLEANLIB-468 tolerant deserializer for the `verdict` label field — see the
/// field doc on [`Verdict::verdict`]. Accepts a flat string (scan / cache / v1)
/// or the envelope-v2 nested object (returns its `type`). Format-aware so bincode
/// (non-self-describing) stays a plain positional string read.
fn de_verdict_label<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    struct LabelVisitor;

    impl<'de> serde::de::Visitor<'de> for LabelVisitor {
        type Value = String;

        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            f.write_str("a verdict label string or an envelope-v2 {type,…} object")
        }

        fn visit_str<E>(self, v: &str) -> Result<String, E> {
            Ok(v.to_string())
        }

        fn visit_string<E>(self, v: String) -> Result<String, E> {
            Ok(v)
        }

        // Envelope-v2 Path-A nested object → return its `type`; ignore the rest.
        fn visit_map<A>(self, mut map: A) -> Result<String, A::Error>
        where
            A: serde::de::MapAccess<'de>,
        {
            let mut label = String::new();
            while let Some(key) = map.next_key::<String>()? {
                if key == "type" {
                    label = map.next_value::<String>()?;
                } else {
                    let _ = map.next_value::<serde::de::IgnoredAny>()?;
                }
            }
            Ok(label)
        }
    }

    // JSON (self-describing) can branch on the actual value; bincode cannot do
    // `deserialize_any`, so read it as the plain positional string it was stored as.
    if deserializer.is_human_readable() {
        deserializer.deserialize_any(LabelVisitor)
    } else {
        deserializer.deserialize_string(LabelVisitor)
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct Verdict {
    pub verdict_id: String,
    /// `ALLOWED_NO_FINDINGS` | `VECTOR_VERDICT` | `DM_THRESHOLD_BLOCK` |
    /// `INSUFFICIENT_DATA` per locked Verdict-label enum.
    ///
    /// CLEANLIB-468: tolerant deserialize. The envelope-v2 customer-verdict wire
    /// (Path A) sends `verdict` as a nested OBJECT `{type,status,customer_state}`,
    /// while `POST /v1/scan` (`ScanResult`) and the bincode verdict cache
    /// send/store it as a flat STRING. A bare `String` field errored on the
    /// object — `invalid type: map, expected a string` — the CLEANLIB-462 live
    /// CLI break. [`de_verdict_label`] accepts EITHER form (object → its `type`;
    /// string → as-is) and is format-aware via `is_human_readable`: JSON uses the
    /// string-or-map visitor, bincode (non-self-describing, positional) uses
    /// `deserialize_string` so the cache round-trip is unaffected. Serialize is
    /// unchanged (emits the flat string). No dependency on the App `verdict_label`
    /// field or on deploy ordering.
    #[serde(deserialize_with = "de_verdict_label")]
    pub verdict: String,
    pub source: String,
    pub confidence: f64,
    pub composite_score: u8,
    pub reasoning: String,
    pub similar_to: Vec<String>,
    pub evidence_gaps: Vec<String>,
    pub suggested_actions: Vec<String>,
    pub data_freshness_at: Option<String>,
    pub data_oldest_signal_at: Option<String>,
    pub stale_since_at: Option<String>,
    pub staleness_reason: Option<String>,
    pub computed_at: Option<String>,
    /// App-canonical severity tier (`NONE` | `LOW` | `MEDIUM` | `HIGH` |
    /// `CRITICAL` per `cleanlib-core::Severity`). Cycle-9 Lane-2 M1 close.
    /// `Option<String>` for serde-default tolerance against pre-M1 payloads.
    pub severity: Option<String>,
    /// Coarse gating decision (`ALLOW` | `WARN` | `DENY` |
    /// `RISK_ACCEPTANCE_REQUIRED`). Sister of js/py/go SDK carrying.
    /// Cycle-9 Lane-2 M1 close. Optional for serde-default tolerance.
    #[serde(alias = "policy_decision")]
    pub decision: Option<String>,
    /// Prior-verdict comparison shape; envelope emits `null` when no prior
    /// verdict exists. v0.1.3 parity-ripple with `sdk-go::PreviousVerdict`
    /// (cycle-13 M1' ship). NOTE: no `skip_serializing_if` — Verdict is
    /// bincode-serialized by `cleanlib-cli` PersistentCache, which is
    /// positional and breaks if fields are conditionally omitted. JSON
    /// consumers see `previous_verdict: null` which matches the App's
    /// canonical envelope shape.
    pub previous_verdict: Option<PreviousVerdict>,
    /// Cycle-15 observability honesty signal. Non-Optional per CLEANLIB-104
    /// App-3.1 Gate M3 flip (2026-07-01). Sister of
    /// `cleanlib_core::AvailabilityBlock`.
    ///
    /// Serde `#[serde(default)]` at the struct level (line 21) provides
    /// fail-open: pre-M3 payloads omitting the `availability` key
    /// deserialize to `AvailabilityBlock::default()` (`degraded_stale = false`).
    /// This preserves compatibility with pre-cycle-15 payloads AND happy-path
    /// verdicts that previously omitted the block via `None`.
    pub availability: AvailabilityBlock,

    // ─── CLEANLIB-412 envelope-v2 (Step-6 phase-a struct prep) ───────────────
    // Additive top-level fields per the BD-ratified emit-boundary contract
    // (CLEANLIB-377 [STEP-EMIT-DRAFT-3] 721058; micro-1 721008 / micro-2 721024).
    // All `Option` + the struct-level `#[serde(default)]` above → pre-envelope-v2
    // (v1) payloads deserialize with `None` (back-compat), and forward-compat holds
    // with NO `deny_unknown_fields` (canvas §7 anti-pattern #7). Wire values stay
    // String; typed parsing (customer_state → STATE_META) remains in
    // `customer_state.rs` via `CustomerState::from_wire`, so an unknown future 9th
    // value never fails the reader. Appended at the tail to keep the bincode
    // (cleanlib-cli PersistentCache) field order stable for existing entries;
    // see PR note re: cache invalidation on struct-shape change.
    /// Envelope schema version — `2` on envelope-v2 responses, `None` on v1.
    pub envelope_version: Option<u32>,
    /// Shipped CLEANLIB-178 OUTPUT display taxonomy (`clean` … `blocked_by_policy`),
    /// hoisted server-side so the client skips `from_wire` on the happy path.
    pub customer_state: Option<String>,
    /// Coarse client UX status (`BLOCKED` | `WARN` | `ALLOWED` | `UNKNOWN` |
    /// `RISK_ACCEPTANCE_REQUIRED`).
    pub state: Option<String>,
    /// Producer wire 8-enum (`DM_THRESHOLD_BLOCK` …) — canonical forward name for
    /// `source` (retained above for v1 back-compat).
    pub source_state: Option<String>,
    /// Active policy bundle version, promoted to top-level in v2.
    pub policy_version: Option<String>,
    /// FK (ULID) to the frozen WORM audit record.
    pub audit_record_id: Option<String>,
    /// hex SHA-256 — tamper-evident binding to the audit record's `content_hash`.
    pub audit_record_hash: Option<String>,
}

/// Cycle-15 honesty signal block on the SDK Verdict shape. Mirrors the App
/// wire-shape `cleanlib_core::AvailabilityBlock`. `Option<bool>`-style
/// passthrough for `degraded_stale` so pre-cycle-15 payloads (without the
/// block) deserialize cleanly.
///
/// CLEANLIB-105 App-3.2 M1/M2 additions: `kev` / `epss` /
/// `exploitation_fusion` sub-fields as `Option<String>` (SDK-passthrough
/// per §5 ripple discipline). String tags: `"available"` |
/// `"not_applicable"` | `"unavailable"` | `"degraded_stale"` per
/// `cleanlib_core::FieldAvailability` snake_case serde. `Option` on the
/// SDK side (vs `FieldAvailability` non-Optional on the App side) lets
/// pre-M1 payloads without any sub-field key deserialize cleanly to
/// `None` — the SDK's `derive_status.rs` treats `None` and
/// `"unavailable"` identically (both fail the "== Some(\"available\")"
/// check on lines 76+).
///
/// NOTE: no `skip_serializing_if` on any field — this struct is bincode-
/// serialized (positionally) by `cleanlib-cli::PersistentCache`, and
/// conditional omission would corrupt the cache alignment (§CLEANLIB-104
/// design doc §3.M3 cache-shape note). The parent `Verdict` documents this
/// invariant at the `previous_verdict` field. Fields that need to be omitted
/// from the customer-facing JSON envelope are re-shaped by
/// [`crate::verdict_to_envelope::verdict_to_envelope_v1`] (which is the
/// customer wire path), not by field-level serde attributes here.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]
#[serde(default)]
pub struct AvailabilityBlock {
    pub degraded_stale: bool,
    /// CISA KEV substrate availability tag
    /// (`"available"` | `"not_applicable"` | `"unavailable"` | `"degraded_stale"`).
    pub kev: Option<String>,
    /// FIRST.org EPSS substrate availability tag.
    pub epss: Option<String>,
    /// Composite exploitation-likelihood availability tag.
    pub exploitation_fusion: Option<String>,
}

/// Prior-verdict comparison. Surfaces when the CleanLibrary App has a
/// stored prior verdict for the same `(ecosystem, package, version)` that
/// differs from the current one — useful for AI agents and dashboards
/// that want to flag verdict-state changes since the last fetch.
/// Sister-shape with `cleanlib_sdk_go::PreviousVerdict` and
/// `cleanlib-core::PreviousVerdict` in the App.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct PreviousVerdict {
    pub verdict_id: String,
    pub verdict: String,
    pub computed_at: String,
    pub diff: String,
}

impl Default for Verdict {
    fn default() -> Self {
        Self {
            verdict_id: String::new(),
            verdict: String::new(),
            source: String::new(),
            confidence: 0.0,
            composite_score: 0,
            reasoning: String::new(),
            similar_to: Vec::new(),
            evidence_gaps: Vec::new(),
            suggested_actions: Vec::new(),
            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-412 envelope-v2 (Step-6 phase-a) — absent on v1.
            envelope_version: None,
            customer_state: None,
            state: None,
            source_state: None,
            policy_version: None,
            audit_record_id: None,
            audit_record_hash: None,
        }
    }
}

/// One package identity for policy-preview / scan requests.
///
/// Wire-contract note: the App-side coordinate struct
/// (`cleanlib-app::verbs::PackageRef`, shared by `POST /v1/scan` +
/// `POST /v1/policy/preview`) names this field `package`, not `name`.
/// Serializing the Rust identifier `name` verbatim made the App reject the
/// body with `422 … packages[0]: missing field \`package\``, breaking both
/// `cleanlib scan` and `cleanlib policy preview`. The `#[serde(rename)]` puts
/// `package` on the wire while keeping the `name` identifier that the
/// packages-file parsers in `commands::scan` already construct.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PackageRef {
    pub ecosystem: String,
    #[serde(rename = "package")]
    pub name: String,
    pub version: String,
}

/// Body of `POST /v1/policy/preview` — packages + optional
/// hypothetical policy override (JSON-shaped; YAML-source customers
/// convert client-side).
#[derive(Debug, Clone, Serialize)]
pub struct PolicyPreviewRequest {
    pub packages: Vec<PackageRef>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy: Option<serde_json::Value>,
}

/// Per-package decision returned from `/v1/policy/preview` or
/// embedded in audit entries.
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct PolicyDecision {
    pub ecosystem: String,
    pub package: String,
    pub version: String,
    /// `ALLOW` | `DENY` | `WARN` | `INSUFFICIENT_DATA` | `RISK_ACCEPTANCE_REQUIRED`
    pub decision: String,
    pub reason: String,
    pub verdict_id: Option<String>,
    pub policy_rule_id: Option<String>,
}

/// Response from `POST /v1/policy/preview`.
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct PolicyPreviewResponse {
    pub decisions: Vec<PolicyDecision>,
}

/// Body of `POST /v1/scan` — a batch of package coordinates, no policy.
///
/// Distinct from [`PolicyPreviewRequest`]: `cleanlib scan` previews packages
/// against the customer's *active* policy (verdict-driven, server-side), so it
/// carries no `policy_yaml`. Routing `scan` through `/v1/policy/preview`
/// (which requires `policy_yaml`) was the 422 that hid behind the earlier
/// `package`-field fix.
#[derive(Debug, Clone, Serialize)]
pub struct ScanRequest {
    pub packages: Vec<PackageRef>,
}

/// One entry of the `POST /v1/scan` response. Mirrors the App's
/// `verbs::ScanResult` wire shape: the package coordinate is flattened
/// (`ecosystem` / `package` / `version`) alongside an optional `verdict`
/// (present on success) or `error` string (per-package partial failure —
/// the App resolves each package independently and never fails the whole
/// batch on one miss).
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct ScanResult {
    pub ecosystem: String,
    pub package: String,
    pub version: String,
    pub verdict: Option<Verdict>,
    pub error: Option<String>,
}

/// Response from `POST /v1/scan`. One [`ScanResult`] per requested package.
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct ScanResponse {
    pub results: Vec<ScanResult>,
}

/// One audit log entry returned from `GET /v1/audit`.
///
/// **CLEANLIB-366 — App wire is source of truth.** Mirrors the App-side
/// `AuditRow` (cleanlib-audit-clickhouse) which the App serializes into each
/// element of the `records` array. Prior CLI struct silently dropped fields
/// because names had drifted (`package` vs App's `package_name`, `version` vs
/// `package_version`, `decision` vs `policy_decision`, `reason` vs
/// `reasoning`, `at` vs `request_at`) — with `#[serde(default)]` deserialize
/// succeeded and every field came back empty. Same class as CLEANLIB-348.
///
/// Field names below match `AuditRow` exactly. All fields default-tolerant
/// via struct-level `#[serde(default)]` so partial responses or App-side
/// schema evolution do not force a CLI recompile.
///
/// UUID fields on the App side (`request_id`, `verdict_id`) serialize as
/// hyphenated strings; datetime fields (`request_at`, `verdict_at`,
/// `response_at`, …) serialize as RFC 3339 strings — hence `String` here.
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct AuditEntry {
    // request identification
    pub request_id: String,
    pub correlation_id: String,

    // request shape
    pub ecosystem: String,
    pub package_name: String,
    pub package_version: String,
    pub variant: String,

    // decision
    pub policy_decision: String,
    pub verdict_id: String,
    pub verdict_source: String,
    pub policy_rule_id_matched: String,
    pub risk_acceptance_status: String,
    pub reasoning: String,

    // catalog
    pub gcs_hit: bool,

    // timing (RFC 3339 strings)
    pub request_at: String,
    pub verdict_at: String,
    pub response_at: String,

    // metadata
    pub app_version: String,
}

/// Query-window echo returned inside [`AuditResponse::window`]. Mirrors the
/// App-side `AuditWindow` — echoes the caller's `since` / `until` filter
/// values verbatim (or `None` when the filter was omitted).
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct AuditWindow {
    pub since: Option<String>,
    pub until: Option<String>,
}

/// Response from `GET /v1/audit`. Mirrors the App-side `AuditResponse` in
/// `cleanlib-app::verbs`. See [`AuditEntry`] for the CLEANLIB-366 field-name
/// alignment note.
///
/// `backend_status` is `"wired"` when the App has an `AuditReader` attached
/// and the read succeeded, `"not_wired"` when no reader is configured, or
/// `"read_error"` when the reader errored. CLI callers surface this signal
/// so customers can distinguish "empty because no rows" from "empty because
/// the audit backend is offline".
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct AuditResponse {
    pub window: AuditWindow,
    pub records: Vec<AuditEntry>,
    pub record_count: usize,
    pub per_route: std::collections::BTreeMap<String, usize>,
    pub backend_status: String,
}

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

    #[test]
    fn parses_minimal_verdict() {
        let json = r#"{
            "verdict_id": "01JBYK000",
            "verdict": "ALLOWED_NO_FINDINGS",
            "source": "ALLOWED_NO_FINDINGS"
        }"#;
        let v: Verdict = serde_json::from_str(json).unwrap();
        assert_eq!(v.verdict_id, "01JBYK000");
        assert_eq!(v.verdict, "ALLOWED_NO_FINDINGS");
        assert_eq!(v.confidence, 0.0);
        assert!(v.similar_to.is_empty());
    }

    /// CLEANLIB-468 regression: the live envelope-v2 Path-A wire — where the
    /// top-level `verdict` key is a nested OBJECT and the label rides
    /// `verdict_label` — must deserialize WITHOUT the `invalid type: map,
    /// expected a string` error that broke Ajeet-Yadav's CLI (CLEANLIB-462).
    #[test]
    fn parses_envelope_v2_path_a_wire_with_verdict_object_and_label() {
        let json = r#"{
            "verdict_id": "01JBYK042",
            "verdict": { "type": "VECTOR_VERDICT", "status": "WARN", "customer_state": "vulnerable" },
            "verdict_label": "VECTOR_VERDICT",
            "source": "CVE_FINDING",
            "envelope_version": 2,
            "customer_state": "vulnerable",
            "state": "WARN",
            "source_state": "CVE_FINDING"
        }"#;
        // Must NOT error (the nested `verdict` object is skipped; label read from
        // `verdict_label`).
        let v: Verdict = serde_json::from_str(json)
            .expect("Path-A v2 wire must deserialize — CLEANLIB-468");
        assert_eq!(v.verdict, "VECTOR_VERDICT");
        assert_eq!(v.source, "CVE_FINDING");
        assert_eq!(v.customer_state.as_deref(), Some("vulnerable"));
        assert_eq!(v.source_state.as_deref(), Some("CVE_FINDING"));
    }

    #[test]
    fn parses_full_verdict() {
        let json = r#"{
            "verdict_id": "01JBYK001",
            "verdict": "VECTOR_VERDICT",
            "source": "VECTOR_VERDICT",
            "confidence": 0.98,
            "composite_score": 92,
            "reasoning": "Confirmed malware",
            "similar_to": ["01JBYK999"],
            "evidence_gaps": [],
            "suggested_actions": ["DENY across customers"],
            "data_freshness_at": "2026-05-21T10:00:00Z",
            "computed_at": "2026-05-21T10:01:00Z"
        }"#;
        let v: Verdict = serde_json::from_str(json).unwrap();
        assert_eq!(v.composite_score, 92);
        assert_eq!(v.confidence, 0.98);
        assert_eq!(v.similar_to.len(), 1);
        assert_eq!(v.suggested_actions[0], "DENY across customers");
    }

    #[test]
    fn parses_policy_preview_response() {
        let json = r#"{
            "decisions": [
                {"ecosystem":"npm","package":"left-pad","version":"1.3.0","decision":"ALLOW","reason":"ok"},
                {"ecosystem":"npm","package":"event-stream","version":"3.3.6","decision":"DENY","reason":"malware","verdict_id":"01JBYK999"}
            ]
        }"#;
        let resp: PolicyPreviewResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.decisions.len(), 2);
        assert_eq!(resp.decisions[0].decision, "ALLOW");
        assert_eq!(resp.decisions[1].decision, "DENY");
        assert_eq!(resp.decisions[1].verdict_id.as_deref(), Some("01JBYK999"));
    }

    /// CLEANLIB-366 — deserialize against the App's real wire shape
    /// (`{window, records, record_count, per_route, backend_status}`) and
    /// assert every renamed field (`package_name`, `package_version`,
    /// `policy_decision`, `reasoning`, `request_at`) round-trips a non-empty
    /// value. The pre-fix struct used `entries` + `{package, version,
    /// decision, reason, at}` and silently dropped every field on this
    /// payload because names did not match.
    #[test]
    fn parses_audit_response_matches_app_wire_shape() {
        let json = r#"{
            "window": {"since": "2026-05-22T00:00:00Z", "until": "2026-05-23T00:00:00Z"},
            "records": [{
                "request_id": "01936b8f-3c4a-7a12-9c00-000000000001",
                "correlation_id": "corr-1",
                "customer_ip_hashed": "sha256:aaaa",
                "ecosystem": "npm",
                "package_name": "lodash",
                "package_version": "4.17.21",
                "variant": "default",
                "user_agent": "cleanlib-cli/0.1.4",
                "policy_decision": "ALLOW",
                "verdict_id": "01936b8f-3c4a-7a12-9c00-0000000000aa",
                "verdict_source": "ALLOWED_NO_FINDINGS",
                "policy_rule_id_matched": "rule-42",
                "risk_acceptance_status": "NONE",
                "reasoning": "ok",
                "gcs_hit": true,
                "gcs_object_path": "gs://bucket/obj",
                "bytes_served": 4096,
                "request_at": "2026-05-22T10:00:00Z",
                "ingest_at": null,
                "gcs_at": null,
                "verdict_at": "2026-05-22T10:00:01Z",
                "policy_eval_at": "2026-05-22T10:00:02Z",
                "response_at": "2026-05-22T10:00:03Z",
                "app_version": "1.2.3"
            }],
            "record_count": 1,
            "per_route": {"/v1/customer/verdicts/npm": 1},
            "backend_status": "wired"
        }"#;
        let resp: AuditResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.records.len(), 1);
        assert_eq!(resp.record_count, 1);
        assert_eq!(resp.backend_status, "wired");
        assert_eq!(resp.window.since.as_deref(), Some("2026-05-22T00:00:00Z"));
        assert_eq!(resp.per_route.get("/v1/customer/verdicts/npm"), Some(&1));

        let e = &resp.records[0];
        // Every renamed field must carry a value — the pre-fix struct would
        // have left these empty because the JSON keys did not match.
        assert_eq!(e.request_id, "01936b8f-3c4a-7a12-9c00-000000000001");
        assert_eq!(e.correlation_id, "corr-1");
        assert_eq!(e.ecosystem, "npm");
        assert_eq!(e.package_name, "lodash");
        assert_eq!(e.package_version, "4.17.21");
        assert_eq!(e.variant, "default");
        assert_eq!(e.policy_decision, "ALLOW");
        assert_eq!(e.verdict_id, "01936b8f-3c4a-7a12-9c00-0000000000aa");
        assert_eq!(e.verdict_source, "ALLOWED_NO_FINDINGS");
        assert_eq!(e.policy_rule_id_matched, "rule-42");
        assert_eq!(e.risk_acceptance_status, "NONE");
        assert_eq!(e.reasoning, "ok");
        assert!(e.gcs_hit);
        assert_eq!(e.request_at, "2026-05-22T10:00:00Z");
        assert_eq!(e.verdict_at, "2026-05-22T10:00:01Z");
        assert_eq!(e.response_at, "2026-05-22T10:00:03Z");
        assert_eq!(e.app_version, "1.2.3");
    }

    /// Backend-not-wired path: App emits the honesty signal + empty records.
    /// The CLI must decode `backend_status` (not silently coerce to empty
    /// via a `next_cursor` field that never existed on the wire).
    #[test]
    fn empty_audit_response_carries_backend_status() {
        let json = r#"{
            "window": {"since": null, "until": null},
            "records": [],
            "record_count": 0,
            "per_route": {},
            "backend_status": "not_wired"
        }"#;
        let resp: AuditResponse = serde_json::from_str(json).unwrap();
        assert!(resp.records.is_empty());
        assert_eq!(resp.record_count, 0);
        assert_eq!(resp.backend_status, "not_wired");
        assert!(resp.window.since.is_none());
        assert!(resp.window.until.is_none());
    }

    #[test]
    fn policy_preview_request_omits_none_policy() {
        let req = PolicyPreviewRequest {
            packages: vec![PackageRef {
                ecosystem: "npm".to_string(),
                name: "lodash".to_string(),
                version: "4.17.21".to_string(),
            }],
            policy: None,
        };
        let json = serde_json::to_string(&req).unwrap();
        // None policy should not appear in serialized output
        assert!(!json.contains("policy"));
        assert!(json.contains("lodash"));
    }

    #[test]
    fn policy_preview_request_emits_policy_when_some() {
        let req = PolicyPreviewRequest {
            packages: vec![],
            policy: Some(serde_json::json!({"rules": []})),
        };
        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("\"policy\""));
        assert!(json.contains("\"rules\""));
    }

    #[test]
    fn round_trips_via_json() {
        let v = Verdict {
            verdict_id: "01JBYK002".to_string(),
            verdict: "INSUFFICIENT_DATA".to_string(),
            source: "INSUFFICIENT_DATA".to_string(),
            stale_since_at: Some("2026-04-21T00:00:00Z".to_string()),
            staleness_reason: Some("upstream silent >30d".to_string()),
            ..Default::default()
        };
        let s = serde_json::to_string(&v).unwrap();
        let parsed: Verdict = serde_json::from_str(&s).unwrap();
        assert_eq!(parsed.verdict_id, "01JBYK002");
        assert_eq!(parsed.stale_since_at.as_deref(), Some("2026-04-21T00:00:00Z"));
    }

    // ─── Lane-2 M1 — severity + decision carrying ──────────────────────

    #[test]
    fn verdict_round_trips_severity_and_decision() {
        let v = Verdict {
            verdict_id: "01JM1S001".to_string(),
            verdict: "VECTOR_VERDICT".to_string(),
            source: "VECTOR_VERDICT".to_string(),
            severity: Some("HIGH".to_string()),
            decision: Some("DENY".to_string()),
            ..Default::default()
        };
        let s = serde_json::to_string(&v).unwrap();
        let parsed: Verdict = serde_json::from_str(&s).unwrap();
        assert_eq!(parsed.severity.as_deref(), Some("HIGH"));
        assert_eq!(parsed.decision.as_deref(), Some("DENY"));
    }

    #[test]
    fn verdict_tolerates_missing_severity_and_decision() {
        // Pre-M1 payload shape — no severity/decision fields. Must still parse
        // via serde-default tolerance per the struct's `#[serde(default)]`.
        let pre_m1_json = r#"{
            "verdict_id": "01JM1S002",
            "verdict": "ALLOWED_NO_FINDINGS",
            "source": "ALLOWED_NO_FINDINGS",
            "confidence": 0.95,
            "composite_score": 8,
            "reasoning": "",
            "similar_to": [],
            "evidence_gaps": [],
            "suggested_actions": []
        }"#;
        let v: Verdict = serde_json::from_str(pre_m1_json).expect("pre-M1 shape must still parse");
        assert!(v.severity.is_none());
        assert!(v.decision.is_none());
    }

    #[test]
    fn verdict_decision_canonical_values_match_js_py_go() {
        // Lane-2 M1 acceptance: decision values match js/py/go SDK envelope.
        // Schema-locked set: ALLOW | WARN | DENY | RISK_ACCEPTANCE_REQUIRED.
        for d in ["ALLOW", "WARN", "DENY", "RISK_ACCEPTANCE_REQUIRED"] {
            let v = Verdict {
                decision: Some(d.to_string()),
                ..Default::default()
            };
            let s = serde_json::to_string(&v).unwrap();
            assert!(s.contains(&format!("\"decision\":\"{}\"", d)));
        }
    }

    #[test]
    fn verdict_severity_canonical_values_match_cleanlib_core() {
        // Sister of `cleanlib-core::Severity` enum: NONE | LOW | MEDIUM | HIGH | CRITICAL.
        for sev in ["NONE", "LOW", "MEDIUM", "HIGH", "CRITICAL"] {
            let v = Verdict {
                severity: Some(sev.to_string()),
                ..Default::default()
            };
            let s = serde_json::to_string(&v).unwrap();
            assert!(s.contains(&format!("\"severity\":\"{}\"", sev)));
        }
    }
}