cleanlib-client 0.1.15

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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
//! 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)
        }

        // CLEANLIB-518 (§2): a null verdict label must NOT reject the whole
        // parse (was `invalid type: null, expected a string` — Test 743061).
        // Degrade tolerantly to the empty label, which the status/reason mapper
        // then resolves to the fail-closed (WARN, VERDICT_NOT_YET_ASSESSED)
        // default — byte-parity with sdk-py/js/go, which already tolerate a
        // null/absent label. serde_json routes JSON `null` to `visit_unit`;
        // `visit_none` covers Option-wrapped deserializers for completeness.
        fn visit_unit<E>(self) -> Result<String, E> {
            Ok(String::new())
        }

        fn visit_none<E>(self) -> Result<String, E> {
            Ok(String::new())
        }

        // 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>,
    /// CLEANLIB-496 (C1): the signed attestation the App emits — the full
    /// `SignedAttestation` object `{attestation:{…10 fields…}, signature_b64,
    /// key_id}`. Carried as a passthrough `Value` (not a mirrored typed struct)
    /// so the CLI `--output json`/`--output sarif` can surface it verbatim for
    /// `verify_attestation.py` without duplicating the cosign-signer schema.
    /// `None` on v1 / unsigned responses.
    pub attestation: Option<serde_json::Value>,
    /// CLEANLIB-518 §4: enhanced-verdict `evidence[]` the App emits under the
    /// `CLEANLIB_ENHANCED_VERDICT` flag (typed `Evidence` items in stream1).
    /// Carried as a passthrough `Value` (shape-agnostic) — same tolerant
    /// discipline as `attestation` above — so `verdict_to_envelope` can surface
    /// it verbatim into `rich_data.evidence` ahead of the A-anchor shape
    /// finalizing (CLEANLIB-525). A rigid typed `Vec<Evidence>` can replace this
    /// later without a wire break (additive: unknown fields already tolerated,
    /// no `deny_unknown_fields`). `None` when the flag is off / on v1.
    pub evidence: Option<serde_json::Value>,
    /// CLEANLIB-518 §4: enhanced-verdict `composition{}` object (dependency /
    /// provenance composition breakdown) the App emits under the same flag.
    /// Same passthrough discipline as `evidence` above; surfaced verbatim into
    /// `rich_data.composition`. `None` when absent.
    pub composition: Option<serde_json::Value>,
    /// CLEANLIB-601 (Option B): the App's typed `rich_data` block, preserved so
    /// the CLI `fix` command can read `rich_data.recommended_version` as a typed
    /// field instead of parsing the `suggested_actions` marker string (Option A).
    /// Both A+B are defense-in-depth: the typed field lands cleanly, and the
    /// marker survives even if the App refactors the struct. `None` on v1 /
    /// responses without the block. Appended at the tail to keep bincode
    /// (cleanlib-cli PersistentCache) field order stable for existing entries;
    /// the cache `get()` self-heals on struct-shape change (deser-fail → miss).
    pub rich_data: Option<RichData>,
    /// CLEANLIB-613: the App's `top_findings` block — the per-CVE findings that
    /// back a VECTOR_VERDICT/DENY, each carrying a structured `fixed_version`.
    /// This is the App's ALWAYS-populated remediation source, unlike the
    /// flag-gated `rich_data.recommended_version` (Option B) which was dark in
    /// prod. Previously UNMODELED — so the CLI `fix` command discarded the App's
    /// own answer at deserialize and produced `no_recommendation` for known-
    /// vulnerable packages while exiting 0 (a fail-open). `fix` now reads the
    /// cumulative (max) `top_findings.findings[].fixed_version` as the upgrade
    /// target. Tolerant-passthrough: `Option` + struct-level `#[serde(default)]`,
    /// no `deny_unknown_fields`, so a v1 payload or a future field never fails the
    /// reader. Appended at the tail to keep the bincode (PersistentCache) field
    /// order stable; the cache `get()` self-heals on struct-shape change.
    pub top_findings: Option<TopFindings>,
    /// CLEANLIB-652 (CX-3) part 1: machine-stable reason a verdict is non-clean,
    /// hoisted top-level on envelope-v2 (App `reason_class`). Exactly one of
    /// `CVE_AFFECTING` | `CVE_ON_KEV` | `CVE_ON_RANSOMWARE` | `MALICIOUS_TRIAGE` |
    /// `POLICY_DENY` | `INSUFFICIENT_DATA` | `RANGE_NOT_RESOLVED`, or `None` on a
    /// clean verdict (no reason owed) and on v1. Values are already codename-clean
    /// (e.g. `POLICY_DENY`, not the engine type name) so the MACHINE surface passes
    /// them through verbatim; the HUMAN surface maps to friendly text via
    /// [`crate::customer_state`]-style rendering in `cleanlib-cli`, with a safe
    /// generic for any unknown future value (forward-compat — no
    /// `deny_unknown_fields`). Distinct from `errors::Problem.reason_class`, which
    /// is an RFC-7807 error-branch key on the error path.
    pub reason_class: Option<String>,
    /// CLEANLIB-652 (CX-3) part 1: renderable attestation status (App
    /// `attestation_status`) — `signed` | `signature_absent` as emitted by the App.
    /// `signature_invalid` is reserved for the CLIENT to set when local verification
    /// of [`Verdict::attestation`] fails (producer/consumer split). `None` on v1.
    /// Machine surface passthrough; human surface maps to Signed / Unsigned /
    /// Invalid signature. Appended at the tail to keep the bincode (PersistentCache)
    /// field order stable for existing entries.
    pub attestation_status: Option<String>,
    /// CLEANLIB-652 (CX-3) part 2: per-axis data freshness — the App's nested
    /// `freshness` block (App `verbs::Freshness`) with SEPARATE ages for the CVE,
    /// behavioral, and policy axes, plus `stalest_axis` and `overall_as_of` (= MIN
    /// of the non-null axis ages, Client-confirmed 652 c767287). Additive: it
    /// ENRICHES the existing flat `data_freshness_at` / `data_oldest_signal_at` /
    /// `stale_since_at` fields, it does not replace them. `None` on v1 / pre-part-2.
    /// Tail-appended to keep the bincode (PersistentCache) field order stable.
    #[serde(default)]
    pub freshness: Option<Freshness>,
    /// CLEANLIB-652 (CX-3) part 3a: structured remediation — a single upgrade
    /// target (App `verbs::Remediation`) so the client renders an actionable
    /// upgrade without parsing prose. `None` when no safe upgrade exists (honest —
    /// matches the App's "no fix to recommend" semantics, distinct from
    /// `top_findings[].fixed_version` / `rich_data.recommended_version` which `fix`
    /// still uses). Tail-appended for bincode field-order stability.
    #[serde(default)]
    pub remediation: Option<Remediation>,
}

/// CLEANLIB-652 (CX-3) part 3a: structured remediation (mirrors App
/// `verbs::Remediation`) — the single upgrade target + a per-ecosystem copy-paste
/// command. `target_version` is engine-clean (the composite's effective fix
/// version). All-string + `#[serde(default)]` for tolerant, forward-compat parse.
#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq)]
#[serde(default)]
pub struct Remediation {
    /// The version to upgrade to (upgrading clears every CVE the composite can).
    pub target_version: String,
    /// Per-ecosystem copy-paste upgrade command for the target.
    pub command_hint: String,
}

/// CLEANLIB-652 (CX-3) part 2: the App's nested per-axis `freshness` block
/// (mirrors `verbs::Freshness`). Each axis age is `Option` — under precedence
/// composition only the producing axis carries a timestamp and the others are
/// null; `overall_as_of` = MIN of the non-null axis ages (the verdict is only as
/// fresh as its stalest input). All-optional + `#[serde(default)]` for tolerant,
/// forward-compatible parsing.
#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq)]
#[serde(default)]
pub struct Freshness {
    pub cve_data_at: Option<String>,
    pub behavioral_data_at: Option<String>,
    pub policy_evaluated_at: Option<String>,
    /// Which axis is stalest — drives the `overall_as_of` age.
    pub stalest_axis: Option<String>,
    /// MIN of the non-null per-axis ages.
    pub overall_as_of: Option<String>,
}

/// CLEANLIB-613: the App's `top_findings` block on a customer verdict — the
/// per-CVE findings that back a VECTOR_VERDICT/DENY, plus the KEV / ransomware
/// flags. Modeled so the CLI `fix` command can reach each finding's structured
/// `fixed_version` (the App's always-populated remediation target). Tolerant:
/// `#[serde(default)]`, all-optional, no `deny_unknown_fields`.
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct TopFindings {
    /// Total CVE count backing this verdict (may exceed `findings.len()` when the
    /// App truncates to the top-N; the summary still counts them all).
    pub cve_count: Option<u32>,
    pub on_kev: Option<bool>,
    pub on_ransomware: Option<bool>,
    /// The per-CVE findings. Each carries its own `fixed_version`; the CLI `fix`
    /// command takes the max across these as the cumulative upgrade target.
    pub findings: Vec<Finding>,
}

/// CLEANLIB-613: one CVE finding inside [`TopFindings`]. Only the fields the CLI
/// consumes are typed; the App may add more (tolerated — no `deny_unknown_fields`).
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct Finding {
    pub cve_id: Option<String>,
    /// The version that remediates THIS CVE. `fix` takes the max of these across
    /// findings as the cumulative upgrade target (you must reach at least the
    /// highest per-CVE fix to clear every CVE). `None` when no fix exists yet.
    pub fixed_version: Option<String>,
    pub vulnerable_versions: Option<String>,
    pub severity: Option<String>,
    pub cvss_v3_score: Option<f64>,
}

/// CLEANLIB-601: typed subset of the App's `rich_data` block. Carries the
/// `recommended_version` upgrade target for the CLI `fix` command. `#[serde(default)]`
/// + no `deny_unknown_fields` — other `rich_data` keys (evidence/composition, which
/// the App also hoists to top-level passthrough fields above) are tolerated, and a
/// `rich_data` object missing `recommended_version` deserializes to `None`.
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct RichData {
    /// The App's suggested upgrade target (e.g. `"4.17.21"`). `None` when the
    /// App emits no recommendation for this coordinate.
    pub recommended_version: 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,
            attestation: None,
            // CLEANLIB-518 §4 tolerant-passthrough — absent unless the App
            // enhanced-verdict flag is on.
            evidence: None,
            composition: None,
            // CLEANLIB-601 — absent unless the App emits a rich_data block.
            rich_data: None,
            // CLEANLIB-613 — absent on v1; populated on customer-verdict responses.
            top_findings: None,
            // CLEANLIB-652 (CX-3) part 1 — absent on v1; App emits on envelope-v2.
            reason_class: None,
            attestation_status: None,
            // CLEANLIB-652 (CX-3) part 2 — nested per-axis freshness; absent on v1.
            freshness: None,
            // CLEANLIB-652 (CX-3) part 3a — structured remediation; absent on v1.
            remediation: 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,
    /// CLEANLIB-666: the `/v1/policy/preview` wire names this `reasoning`
    /// (`verbs::PolicyPreviewResult.reasoning`); scan/audit surfaces use `reason`.
    /// Alias reads both so the same struct parses every producer.
    #[serde(alias = "reasoning")]
    pub reason: String,
    pub verdict_id: Option<String>,
    /// CLEANLIB-666: `/v1/policy/preview` names the matched rule `matched_rule_id`
    /// on the wire; other surfaces use `policy_rule_id`. Alias reads both.
    #[serde(alias = "matched_rule_id")]
    pub policy_rule_id: Option<String>,
    /// CLEANLIB-616: set when this coordinate could NOT be evaluated — a per-package
    /// scan error, or a chunk that failed/returned no result (mirrors
    /// `ScanResult.error`). Lets `--output json` distinguish a NEVER-EVALUATED
    /// coordinate from one that was evaluated and warned: both surface as a WARN
    /// `decision`, but only the unevaluated one carries `error`. `None` (and
    /// omitted from JSON) on an evaluated coordinate.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Response from `POST /v1/policy/preview`.
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct PolicyPreviewResponse {
    /// CLEANLIB-666: the App emits this array as `results`
    /// (`verbs::PolicyPreviewResponse.results`), not `decisions`. Without the
    /// alias the client parsed every real preview response into an EMPTY vec —
    /// the verb silently returned nothing (exit 0) even after CLEANLIB-631/#362
    /// fixed the request side. Alias makes the client read the real wire.
    #[serde(alias = "results")]
    pub decisions: Vec<PolicyDecision>,
    /// CLEANLIB-666 residual: the App emits `policy_version` alongside `results`
    /// (`verbs::PolicyPreviewResponse.policy_version`) — the version of the policy
    /// these decisions were evaluated against. The response struct previously had
    /// no field for it, so it was silently dropped (gate376 flagged
    /// `policy_version DROPPED`). Capture it so `--output json` faithfully reports
    /// which policy version produced the decisions. `#[serde(default)]` on the
    /// struct keeps this back-compat for responses that omit it (→ `None`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy_version: Option<String>,
}

/// 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>,
    // ─── CLEANLIB-652 [SibSurface] (#372): per-package v2 envelope fields ─────
    // App #372 flattens a ScanVerdictEnvelope onto each ScanResult, so these ride
    // as SIBLINGS of `verdict` (which stays nested) — the client dropped them
    // before this. All `Option` + the struct-level `#[serde(default)]` → v1 / thin
    // results deserialize `None` (back-compat), no `deny_unknown_fields`. Names
    // mirror the App wire exactly. Reuses [`Freshness`]/[`Remediation`] (CX-3
    // part-2/3a). Surfaced on the scan surface via `decision_from_result`.
    pub customer_state: Option<String>,
    pub state: Option<String>,
    pub source_state: Option<String>,
    pub reason_class: Option<String>,
    pub attestation_status: Option<String>,
    pub freshness: Option<Freshness>,
    pub remediation: Option<Remediation>,
}

/// CLEANLIB-652 (CX-3) part 3b / CLEANLIB-647 (DD-1): one per-coordinate
/// not-assessed reason from the App's per-request `coverage` block. The App emits
/// this for every coordinate it returned but could NOT assess (see
/// [`Coverage::not_assessed_reasons`]); the client joins it into the per-decision
/// `error` field so `scan --output json` can distinguish a NEVER-EVALUATED
/// coordinate from one that was evaluated and warned.
#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq)]
#[serde(default)]
pub struct NotAssessedReason {
    /// `"{ecosystem}/{package}@{version}"` — the App's coordinate identity,
    /// matching the client's own `format!("{}/{}@{}", …)` join key.
    pub coordinate: String,
    /// Coverage-scoped reason class (`INSUFFICIENT_DATA` | `RANGE_NOT_RESOLVED`).
    pub reason_class: String,
}

/// CLEANLIB-652 (CX-3) part 3b / CLEANLIB-647 (DD-1): the App's per-request
/// `coverage` block on the `POST /v1/scan` response — how many coordinates were
/// assessed vs not, plus the per-coordinate attribution the client required
/// (652 c767287) so DD-1 can populate `error` on each never-evaluated coordinate.
#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq)]
#[serde(default)]
pub struct Coverage {
    pub assessed: usize,
    pub not_assessed: usize,
    /// Per-coordinate reasons; empty (and omitted on the wire) when every
    /// coordinate was assessed.
    pub not_assessed_reasons: Vec<NotAssessedReason>,
}

/// 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>,
    /// CLEANLIB-652 (CX-3) part 3b: per-request coverage. `None` on v1 / pre-part-3b
    /// responses (struct-level `#[serde(default)]` → back-compat).
    pub coverage: Option<Coverage>,
    /// CLEANLIB-669 [SibSurface-pre-emption]: the active policy-bundle version for
    /// this scan request — the App emits it TOP-LEVEL on the /v1/scan response
    /// (sibling of `results`/`coverage`, App PR #378), per-request not per-result.
    /// Without this field the client silently DROPS it at parse (the same
    /// App-emit-needs-Client-consume pairing as [SibSurface]). `None` on v1 /
    /// envelope-v2-off (`#[serde(default)]` → back-compat).
    pub policy_version: Option<String>,
}

/// 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 cleanlib_613_parses_top_findings_fixed_version() {
        // Locks the wire contract for the CLI `fix` remediation source. Captured
        // from cleanapp.clnstrt.dev/v1/customer/verdicts/npm/lodash/4.17.20
        // (2026-08-20): `verdict` is a nested object, `rich_data` is null, and the
        // remediation target lives in `top_findings.findings[].fixed_version`.
        let json = r#"{
            "verdict_id": "01JBYK613",
            "verdict": {"customer_state":"vulnerable","status":"WARN","type":"VECTOR_VERDICT"},
            "source": "CVE_FINDING",
            "rich_data": null,
            "suggested_actions": ["Upgrade to 4.18.0+ to address CVE-2026-4800 (HIGH, CVSS 8.1)"],
            "top_findings": {
                "cve_count": 6,
                "on_kev": false,
                "on_ransomware": false,
                "findings": [
                    {"cve_id":"CVE-2026-4800","fixed_version":"4.18.0","vulnerable_versions":">=4.0.0,<4.18.0","severity":"HIGH","cvss_v3_score":8.1},
                    {"cve_id":"CVE-2021-23337","fixed_version":"4.17.21","severity":"HIGH"}
                ]
            }
        }"#;
        let v: Verdict = serde_json::from_str(json).unwrap();
        // The nested-object `verdict` still deserializes to its `type` (de_verdict_label).
        assert_eq!(v.verdict, "VECTOR_VERDICT");
        assert!(v.rich_data.is_none());
        let tf = v.top_findings.expect("top_findings must parse");
        assert_eq!(tf.cve_count, Some(6));
        assert_eq!(tf.findings.len(), 2);
        assert_eq!(tf.findings[0].fixed_version.as_deref(), Some("4.18.0"));
        assert_eq!(tf.findings[0].cve_id.as_deref(), Some("CVE-2026-4800"));
        // A finding omitting optional fields still parses (serde default tolerance).
        assert_eq!(tf.findings[1].fixed_version.as_deref(), Some("4.17.21"));
        assert!(tf.findings[1].cvss_v3_score.is_none());
    }

    #[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"));
    }

    #[test]
    fn cleanlib_601_preserves_rich_data_recommended_version() {
        // The App's rich_data.recommended_version must survive deserialization into
        // the typed field (was silently dropped — no field for it). Extra rich_data
        // keys are tolerated (no deny_unknown_fields).
        let json = r#"{
            "verdict_id": "01JBYK601",
            "verdict": "VECTOR_VERDICT",
            "source": "VECTOR_VERDICT",
            "rich_data": { "recommended_version": "4.17.21", "some_other_key": 7 }
        }"#;
        let v: Verdict = serde_json::from_str(json).unwrap();
        assert_eq!(
            v.rich_data
                .as_ref()
                .and_then(|r| r.recommended_version.as_deref()),
            Some("4.17.21")
        );

        // Absent rich_data → None (v1 back-compat, struct-level serde default).
        let v1: Verdict =
            serde_json::from_str(r#"{"verdict_id":"x","verdict":"ALLOWED_NO_FINDINGS","source":"x"}"#)
                .unwrap();
        assert!(v1.rich_data.is_none());
    }

    // ─── 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)));
        }
    }
}