cleanlib-client 0.3.0

HTTP client SDK for the CleanLibrary verdict API — VerdictEnvelopeV1 types, derive_status logic, transport, config, and risk-acceptance YAML emitter shared between cleanlib-cli and other CleanLibrary consumers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
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
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
//! 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-780: the per-axis result envelope (App `axes`), reporting the
    /// advisory / threat / availability planes SEPARATELY so a consulted-and-empty
    /// advisory reads as an honest GREEN ("checked, none found") rather than an
    /// alarmist data-gap, and a behavioral-malicious signal is not collapsed into
    /// the advisory verdict. v2-gated + skip-None on the wire → `None` on v1.
    /// Tail-appended for bincode (PersistentCache) field-order stability; the cache
    /// `get()` self-heals on struct-shape change (deser-fail → miss). See [`Axes`].
    #[serde(default)]
    pub axes: Option<Axes>,
    /// CLEANLIB-855: the policy rule ID that produced a `DM_THRESHOLD_BLOCK`/
    /// `DM_THRESHOLD_WARN` verdict, when one did. `None` on every other
    /// source (Vector/CVE/absence paths never match a customer policy rule)
    /// and on pre-855 App builds. A curated `supply-chain-compromise-bridge-*`
    /// prefix distinguishes a `Compromised` render from the generic
    /// `BlockedByPolicy` — see [`crate::customer_state::CustomerState::
    /// from_block_origin`] and [`crate::customer_state::is_curated_supply_chain_compromise`].
    /// Tail-appended for bincode (PersistentCache) field-order stability.
    #[serde(default)]
    pub matched_rule_id: Option<String>,
}

/// 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.
///
/// CLEANLIB-755/745: this struct used to carry ONLY `target_version` +
/// `command_hint` — every other field the App's `verbs::Remediation` emits
/// (`screened_at`, `peer_compatibility_checked`/`_note`, `clears`,
/// `still_open`, `compatibility`) parsed successfully (serde silently drops
/// unknown JSON keys with no `deny_unknown_fields`) but was then LOST on
/// every re-serialize through this narrower client-side type — the exact
/// mechanism behind two "already fixed" tickets both reproducing unchanged
/// via `cleanlib verdict --output json`/`cleanlib fix`: 755's `screened_at`
/// and 745's `peer_compatibility_checked`/`_note` disclosure. The App-side
/// fields were genuinely wired (verified: `build_remediation` in
/// `cleanlib-app/src/http.rs` sets them); the CLI just never had anywhere to
/// put them. Widened to full parity with the wire shape so this class of
/// silent-drop can't recur field-by-field, ticket-by-ticket ([SibSurface]).
#[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,
    /// CVE ids the target clears.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub clears: Vec<String>,
    /// CVE ids the target does NOT clear (findings with no known fix).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub still_open: Vec<String>,
    /// Compatibility label for the version jump. `Unknown` (the safe default,
    /// matching the App's own "undetermined ≠ same_major" discipline) when
    /// the server omitted it (a pre-702 App build) or the value was absent.
    #[serde(default)]
    pub compatibility: Compatibility,
    /// CLEANLIB-755: the advisory CONSULTATION time the target was screened
    /// against (not the request-compute stamp — see the App-side doc comment
    /// on `verbs::Remediation::screened_at`). `None` when nothing was
    /// consulted or the server didn't set it (omit, never fabricate "now").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub screened_at: Option<String>,
    /// CLEANLIB-745 (Bug 1): whether `target_version` was checked against
    /// peerDependencies declared elsewhere in the customer's tree. This API
    /// surface never receives the customer's lockfile, so it is `false` on
    /// every target the App emits today — carried through here so a direct
    /// API/MCP/CLI consumer of `verdict`/`remediation` sees the caveat
    /// instead of treating an isolated-safe target as tree-safe.
    #[serde(default)]
    pub peer_compatibility_checked: bool,
    /// Companion to `peer_compatibility_checked`: the reason, when `false`.
    /// `None` on a pre-745 App build (omit, don't fabricate an explanation).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub peer_compatibility_note: Option<String>,
}

/// CLEANLIB-702 remediation compatibility label — mirrors App
/// `verbs::Compatibility` (`#[serde(rename_all = "snake_case")]`) wire-for-wire.
/// `Unknown` is the `Default` (and the safe fallback for an unrecognized/absent
/// wire value): an undetermined compatibility must never silently read as the
/// reassuring `SameMajor`.
#[derive(Debug, Clone, Copy, Deserialize, Serialize, Default, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Compatibility {
    /// Drop-in within the pinned compatibility boundary.
    SameMajor,
    /// A breaking move across the compatibility boundary, either direction.
    MajorBump,
    /// Compatibility could not be determined (e.g. an unparseable version).
    #[default]
    Unknown,
}

/// 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>,
}

/// CLEANLIB-780: the per-axis result envelope (mirrors the App's `axes` on
/// `CustomerVerdictResponse`). Each plane is reported SEPARATELY so the client
/// renders honest per-axis language. Tolerant: struct-level `#[serde(default)]` +
/// `Default`, no `deny_unknown_fields`, so a partial or future-extended envelope
/// never fails the reader.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]
#[serde(default)]
pub struct Axes {
    pub advisory: AxisAdvisory,
    pub threat: AxisThreat,
    pub availability: AxisAvailability,
}

/// CLEANLIB-780 advisory (CVE cross-reference) axis. `result` is the App's
/// closed enum `clean` | `vulnerable` | `never_consulted` — DERIVED, never a
/// false clean. `sources_consulted` lists ONLY sources proven to have
/// contributed data and is ABSENT on a clean/empty result (the App does not
/// fabricate a source list), so the client must render only the sources present
/// and never a hardcoded set.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]
#[serde(default)]
pub struct AxisAdvisory {
    pub ran: bool,
    pub result: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sources_consulted: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub consulted_at: Option<String>,
    pub advisory_count: usize,
}

/// CLEANLIB-780 threat (behavioral / Vector triage) axis — the empirical split
/// from advisory. `result` is `malicious` | `blocked` | `clean` |
/// `never_consulted`. CVE findings are the ADVISORY axis and are NOT counted here.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]
#[serde(default)]
pub struct AxisThreat {
    pub ran: bool,
    pub result: String,
    pub finding_count: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub evaluated_at: Option<String>,
}

/// CLEANLIB-780 availability (byte-serve fingerprint) axis. Not evaluated on the
/// verdict path, so `ran` is honestly `false` — a scope statement, not a failure.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]
#[serde(default)]
pub struct AxisAvailability {
    pub ran: bool,
    pub result: 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,
            // CLEANLIB-780 — per-axis result envelope; absent on v1.
            axes: None,
            // CLEANLIB-855 — matched policy rule; absent on v1 and on any
            // non-policy verdict source.
            matched_rule_id: 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>,
    /// CLEANLIB-480 · the `x-request-id` header the App emits on every
    /// response (per CLEANLIB-470, live on all 4 response classes). Populated
    /// from the RESPONSE HEADER by `transport::Client::policy_preview` after
    /// the JSON body has been parsed — the wire body itself carries no
    /// `request_id` field (`#[serde(default)]` → `None` on deserialize).
    /// SDK callers doing correlation debugging (e.g. partner reporting an
    /// issue, log correlation) read this directly instead of falling back
    /// to a raw HTTP client bypass.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_id: 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>,
    /// CLEANLIB-480 · the `x-request-id` header the App emits on every
    /// response — populated from the RESPONSE HEADER by
    /// `transport::Client::scan`. See [`PolicyPreviewResponse::request_id`]
    /// for the rationale.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_id: 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 when populated; datetime fields (`request_at`,
/// `verdict_at`, `response_at`, …) serialize as RFC 3339 strings — hence
/// `String` for those. `request_id` / `verdict_id` are `Option<String>` —
/// see [`deserialize_optional_audit_id_normalize_nil`] for why (CLEANLIB-743
/// / CLEANLIB-813, 2026-09-15 crash fix).
///
/// CLEANLIB-794 (App-side) — defensive [Degr≡Real] guard for the App's
/// `request_id` / `verdict_id` placeholders on audit records.
///
/// The persisted ClickHouse audit row historically carries no real
/// `request_id` / `verdict_id` for these rows (the WORM decision SoR doesn't
/// capture them). The App used to emit the nil-UUID
/// (`"00000000-0000-0000-0000-000000000000"`) as a stand-in, which forwarded
/// to callers as if it were a real per-record identifier (the CLI's audit
/// table showed every row with the same fake ULID). The App's own CLEANLIB-794
/// fix now masks that nil-UUID to a literal JSON `null` at the customer
/// serialization boundary (`mask_placeholder_uuids_in_audit_row` in
/// `cleanlib-app::verbs`) — which is an HONEST wire signal, but this struct
/// declared both fields as plain non-optional `String` with (at most) a
/// nil-UUID-*string* normalizer, so a literal `null` hard-failed
/// deserialization: `invalid type: null, expected a string`. Verified this
/// crashes the real published `cleanlib-cli 0.1.21` / `cleanlib-client 0.2.0`
/// against real production data — `cleanlib audit` could not complete at
/// ALL, filtered or not (CLEANLIB-743 retroactive audit, CLEANLIB-813 same
/// root cause via the `until` filter). Fixed here by making both fields
/// `Option<String>`, `None` meaning "no id recorded for this row" — the
/// same honest-absence contract the rest of this file already uses
/// everywhere else (see [`Verdict`]'s many `Option<String>` fields).
fn deserialize_optional_audit_id_normalize_nil<'de, D>(
    deserializer: D,
) -> Result<Option<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::Deserialize;
    // Field may be absent (struct-level `#[serde(default)]` → None before
    // this function even runs), a literal JSON `null` (the App's CLEANLIB-794
    // boundary mask — the crash case this fixes), the legacy nil-UUID
    // *string* placeholder (defense-in-depth for any code path that still
    // emits the old sentinel instead of `null`), an empty string, or a real
    // id. The first four all normalize to `None`; anything else passes
    // through as `Some(value)`. Consolidating empty-string into `None` too
    // (rather than keeping it as a distinct third "honest absence" shape)
    // gives every caller ONE canonical way to check "was this stamped?":
    // `.is_some()`.
    let raw: Option<String> = Option::deserialize(deserializer)?;
    match raw {
        None => Ok(None),
        Some(s) if s.is_empty() => Ok(None),
        Some(s) if s == "00000000-0000-0000-0000-000000000000" => Ok(None),
        Some(s) => Ok(Some(s)),
    }
}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct AuditEntry {
    // request identification
    /// `None` when the App has no per-request id for this row (either a
    /// literal wire `null` — CLEANLIB-794's boundary mask — or the legacy
    /// nil-UUID string placeholder). `Some(id)` for a genuinely stamped
    /// request. CLEANLIB-743/813 (2026-09-15): was plain non-optional
    /// `String`, which hard-crashed `cleanlib audit` against real production
    /// data the moment the App started emitting `null` for this field.
    #[serde(deserialize_with = "deserialize_optional_audit_id_normalize_nil")]
    pub request_id: Option<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,
    /// `None` when the WORM decision SoR behind this audit row carries no
    /// verdict id (same class as `request_id` above — App CLEANLIB-794 masks
    /// its nil-UUID placeholder to `null` at the wire boundary).
    /// CLEANLIB-743/813 (2026-09-15): was plain non-optional `String` with no
    /// deserializer at all — the actual crash site Test-mgr's live repro hit
    /// first (`verdict_id` appears earlier than `request_id` in the App's
    /// real field order).
    #[serde(deserialize_with = "deserialize_optional_audit_id_normalize_nil")]
    pub verdict_id: Option<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,
    /// CLEANLIB-480 · the `x-request-id` header the App emits on every
    /// response — populated from the RESPONSE HEADER by
    /// `transport::Client::audit`. Distinct from [`AuditEntry::request_id`]
    /// (which is the record-scoped request identifier PERSISTED PER ROW);
    /// this is the ULID of the current `GET /v1/audit` call that returned
    /// this response body. See [`PolicyPreviewResponse::request_id`] for
    /// the rationale.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_id: Option<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());
    }

    #[test]
    fn cleanlib_780_v1_verdict_has_no_axes() {
        // Back-compat: a v1 payload omits `axes` -> None (never a parse error).
        let json = r#"{"verdict_id":"01A","verdict":"ALLOWED_NO_FINDINGS","source":"ALLOWED_NO_FINDINGS"}"#;
        let v: Verdict = serde_json::from_str(json).unwrap();
        assert!(v.axes.is_none());
    }

    #[test]
    fn cleanlib_780_parses_axes_consulted_empty_clean() {
        // The GREEN-flip case: advisory consulted + empty -> result "clean" with
        // the sources that PROVABLY contributed. Mirrors App's #477 wire exactly.
        let json = r#"{
            "verdict_id":"01B","verdict":"ALLOWED_NO_FINDINGS","source":"ALLOWED_NO_FINDINGS",
            "axes":{
                "advisory":{"ran":true,"result":"clean","sources_consulted":["cve","nvd","ghsa"],"consulted_at":"2026-09-02T08:00:00Z","advisory_count":0},
                "threat":{"ran":true,"result":"clean","finding_count":0,"evaluated_at":"2026-09-02T08:00:00Z"},
                "availability":{"ran":false,"result":"not_run"}
            }
        }"#;
        let v: Verdict = serde_json::from_str(json).unwrap();
        let axes = v.axes.expect("axes present under v2");
        assert_eq!(axes.advisory.result, "clean");
        assert_eq!(axes.advisory.sources_consulted.as_deref(), Some(&["cve".to_string(),"nvd".to_string(),"ghsa".to_string()][..]));
        assert_eq!(axes.advisory.consulted_at.as_deref(), Some("2026-09-02T08:00:00Z"));
        assert_eq!(axes.advisory.advisory_count, 0);
        assert_eq!(axes.threat.result, "clean");
        assert!(!axes.availability.ran);
    }

    #[test]
    fn cleanlib_780_parses_axes_never_consulted_no_sources() {
        // never_consulted: sources_consulted ABSENT (App does not fabricate a
        // source list) -> None, so the client renders no source enumeration.
        let json = r#"{
            "verdict_id":"01C","verdict":"INSUFFICIENT_DATA","source":"INSUFFICIENT_DATA",
            "axes":{
                "advisory":{"ran":false,"result":"never_consulted","advisory_count":0},
                "threat":{"ran":false,"result":"never_consulted","finding_count":0},
                "availability":{"ran":false,"result":"not_run"}
            }
        }"#;
        let v: Verdict = serde_json::from_str(json).unwrap();
        let axes = v.axes.expect("axes present");
        assert_eq!(axes.advisory.result, "never_consulted");
        assert!(axes.advisory.sources_consulted.is_none(), "no fabricated source list");
        assert!(axes.advisory.consulted_at.is_none());
    }

    /// 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.as_deref(),
            Some("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.as_deref(),
            Some("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)));
        }
    }

    // ─── CLEANLIB-743/813 · AuditEntry.request_id / verdict_id null-tolerance ──
    // (supersedes the narrower CLEANLIB-794 nil-UUID-string-only coverage below)

    /// THE counterexample that was missing before this fix shipped: a literal
    /// JSON `null` on BOTH `request_id` and `verdict_id`, in the exact shape
    /// Test-mgr's live retroactive audit captured from real production
    /// (`invalid type: null, expected a string`) after the App's CLEANLIB-794
    /// fix started masking its nil-UUID placeholder to `null` at the wire
    /// boundary. FAILS on the pre-fix build (plain non-optional `String` on
    /// both fields — hard deserialize error, not a graceful default). PASSES
    /// post-fix: both fields deserialize to `None`, sibling fields untouched.
    #[test]
    fn cleanlib_743_audit_entry_tolerates_literal_null_request_id_and_verdict_id() {
        let json = r#"{"request_id": null,
                       "verdict_id": null,
                       "correlation_id": "01M2J6R8J5QDQXGE43GW6MMPTZ",
                       "ecosystem": "npm",
                       "package_name": "exceljs",
                       "package_version": "4.4.0",
                       "policy_decision": "ALLOW",
                       "policy_rule_id_matched": "allow-default",
                       "reasoning": "ALLOW_BY_ABSENCE -- no live vulnerability findings",
                       "request_at": "2026-08-31T05:52:40.003567Z"}"#;
        let e: AuditEntry = serde_json::from_str(json)
            .expect("a literal null request_id/verdict_id must not crash deserialize");
        assert!(e.request_id.is_none());
        assert!(e.verdict_id.is_none());
        // [SibFields] guard — the fix must not touch anything else.
        assert_eq!(e.correlation_id, "01M2J6R8J5QDQXGE43GW6MMPTZ");
        assert_eq!(e.package_name, "exceljs");
        assert_eq!(e.policy_decision, "ALLOW");
    }

    /// The exact wire shape `cleanlib audit` (no flags) receives from real
    /// production per Test-mgr's 2026-09-15 repro: a full, otherwise-healthy
    /// `AuditResponse` envelope where every record's `request_id` /
    /// `verdict_id` is `null`. Exercises the whole response type, not just
    /// one record, and is the shape `cleanlib-cli::commands::audit::run`
    /// actually parses.
    #[test]
    fn cleanlib_743_audit_response_survives_null_ids_on_every_record() {
        let json = r#"{
            "window": {"since": null, "until": null},
            "records": [
                {"request_id": null, "verdict_id": null, "ecosystem": "npm",
                 "package_name": "lodash", "package_version": "4.17.15",
                 "policy_decision": "DENY"},
                {"request_id": null, "verdict_id": null, "ecosystem": "npm",
                 "package_name": "axios", "package_version": "1.6.0",
                 "policy_decision": "DENY"}
            ],
            "record_count": 2,
            "per_route": {},
            "backend_status": "wired"
        }"#;
        let resp: AuditResponse =
            serde_json::from_str(json).expect("500 real-shaped null-id records must parse");
        assert_eq!(resp.records.len(), 2);
        assert!(resp.records.iter().all(|r| r.request_id.is_none()));
        assert!(resp.records.iter().all(|r| r.verdict_id.is_none()));
    }

    /// Counterexample: the App-side legacy placeholder must still NOT reach
    /// the SDK caller as a fake id (defense-in-depth for any code path that
    /// emits the nil-UUID STRING instead of the newer `null` mask). Every
    /// `request_id` / `verdict_id` equal to the nil-UUID string normalizes to
    /// `None` on deserialize — same outcome as a literal `null`.
    #[test]
    fn cleanlib_794_audit_entry_nil_uuid_string_normalizes_to_none() {
        let json = r#"{"request_id": "00000000-0000-0000-0000-000000000000",
                       "verdict_id": "00000000-0000-0000-0000-000000000000",
                       "ecosystem": "npm",
                       "package_name": "lodash",
                       "package_version": "4.17.21",
                       "policy_decision": "ALLOW"}"#;
        let e: AuditEntry = serde_json::from_str(json).unwrap();
        assert!(
            e.request_id.is_none(),
            "nil-UUID string must fold to None; pre-fix would surface the fake id verbatim"
        );
        assert!(e.verdict_id.is_none(), "same fold applies to verdict_id");
        // Sibling fields must NOT be touched — the normalizer scoped to
        // request_id/verdict_id only. [SibFields] guard.
        assert_eq!(e.package_name, "lodash");
        assert_eq!(e.ecosystem, "npm");
        assert_eq!(e.policy_decision, "ALLOW");
    }

    /// A real ULID / UUID must pass through unchanged — the normalizer must
    /// not accidentally reject any non-nil value, for either field.
    #[test]
    fn cleanlib_794_audit_entry_real_ids_pass_through() {
        let json = r#"{"request_id": "01936b8f-3c4a-7a12-9c00-000000000001",
                       "verdict_id": "01936b8f-3c4a-7a12-9c00-0000000000aa",
                       "ecosystem": "npm",
                       "package_name": "lodash"}"#;
        let e: AuditEntry = serde_json::from_str(json).unwrap();
        assert_eq!(
            e.request_id.as_deref(),
            Some("01936b8f-3c4a-7a12-9c00-000000000001")
        );
        assert_eq!(
            e.verdict_id.as_deref(),
            Some("01936b8f-3c4a-7a12-9c00-0000000000aa")
        );
    }

    /// A missing `request_id` / `verdict_id` key deserializes as `None` — same
    /// outcome as the nil-UUID fold and the literal-`null` case, so callers
    /// see one honest "absent" signal regardless of how the App represents it
    /// on the wire.
    #[test]
    fn cleanlib_794_audit_entry_missing_ids_are_none() {
        let json = r#"{"ecosystem": "npm", "package_name": "lodash"}"#;
        let e: AuditEntry = serde_json::from_str(json).unwrap();
        assert!(e.request_id.is_none());
        assert!(e.verdict_id.is_none());
    }

    /// An empty string on the wire is folded into the same `None` outcome —
    /// there is now exactly one canonical "absent" representation
    /// (`.is_none()`), not three different ones a caller would have to check.
    #[test]
    fn cleanlib_794_audit_entry_empty_string_id_normalizes_to_none() {
        let json = r#"{"request_id": "", "verdict_id": "", "ecosystem": "npm", "package_name": "lodash"}"#;
        let e: AuditEntry = serde_json::from_str(json).unwrap();
        assert!(e.request_id.is_none());
        assert!(e.verdict_id.is_none());
    }

    // ─── CLEANLIB-755/745: Remediation no longer silently drops server fields ──

    /// COUNTEREXAMPLE per interview-discipline gate: the EXACT live production
    /// shape (npm/eslint@7.32.0 via the App's real `verbs::Remediation` wire
    /// shape). On the pre-fix 2-field struct (`target_version`+`command_hint`
    /// only), `screened_at` and `peer_compatibility_checked`/`_note` parse
    /// successfully (serde drops unknown keys) but vanish on re-serialize —
    /// exactly what `cleanlib verdict --output json` showed Test-mgr on
    /// 2026-09-15. This test FAILS on the pre-fix struct and PASSES only once
    /// every field round-trips.
    #[test]
    fn cleanlib_755_745_remediation_round_trips_every_server_field() {
        let json = r#"{
            "target_version": "9.26.0",
            "command_hint": "npm install eslint@9.26.0",
            "clears": [],
            "still_open": [],
            "compatibility": "major_bump",
            "screened_at": "2026-09-15T10:55:00Z",
            "peer_compatibility_checked": false,
            "peer_compatibility_note": "this target was selected from advisory data only..."
        }"#;
        let r: Remediation = serde_json::from_str(json).unwrap();
        assert_eq!(r.target_version, "9.26.0");
        assert_eq!(r.compatibility, Compatibility::MajorBump);
        assert_eq!(r.screened_at.as_deref(), Some("2026-09-15T10:55:00Z"));
        assert!(!r.peer_compatibility_checked);
        assert!(r.peer_compatibility_note.is_some());

        // Re-serialize (what `--output json` does) must preserve every field.
        let out = serde_json::to_string(&r).unwrap();
        let back: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert_eq!(back["screened_at"], "2026-09-15T10:55:00Z", "755: screened_at must survive re-serialize: {out}");
        assert_eq!(back["peer_compatibility_checked"], false, "745: peer_compatibility_checked must survive re-serialize: {out}");
        assert!(back["peer_compatibility_note"].is_string(), "745: peer_compatibility_note must survive re-serialize: {out}");
        assert_eq!(back["compatibility"], "major_bump");
    }

    /// Absent-field siblings (server omits `screened_at`/`peer_compatibility_note`
    /// because nothing was consulted, or a pre-755/745 App build) must stay
    /// absent — omit, never fabricate — and must NOT fail parsing of the rest
    /// of the struct.
    #[test]
    fn cleanlib_755_745_remediation_tolerates_absent_optional_fields() {
        let json = r#"{"target_version": "1.0.0", "command_hint": "npm install x@1.0.0"}"#;
        let r: Remediation = serde_json::from_str(json).unwrap();
        assert_eq!(r.screened_at, None);
        assert!(!r.peer_compatibility_checked);
        assert_eq!(r.peer_compatibility_note, None);
        assert_eq!(r.compatibility, Compatibility::Unknown, "absent compatibility defaults to Unknown, not SameMajor");

        let out = serde_json::to_string(&r).unwrap();
        assert!(!out.contains("screened_at"), "absent screened_at must be omitted, not null: {out}");
        assert!(!out.contains("peer_compatibility_note"), "absent note must be omitted, not null: {out}");
    }

    /// `Default::default()` (used by every existing struct-literal test
    /// construction across the workspace) must yield the same safe defaults —
    /// `Unknown` compatibility, `false` peer_compatibility_checked, absent
    /// optionals — so old tests that only set target_version/command_hint
    /// keep their original meaning.
    #[test]
    fn cleanlib_755_745_remediation_default_is_the_safe_unset_state() {
        let r = Remediation {
            target_version: "1.0.0".to_string(),
            command_hint: "x".to_string(),
            ..Default::default()
        };
        assert_eq!(r.compatibility, Compatibility::Unknown);
        assert!(!r.peer_compatibility_checked);
        assert_eq!(r.screened_at, None);
        assert_eq!(r.peer_compatibility_note, None);
    }
}