cleanlib-cli 0.1.5

Terminal interface to CleanLibrary — query dependency verdicts and scan package manifests for ALLOW / DENY / WARN signals from the terminal or CI pipelines.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
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
//! CLEANLIB-196 (Client-3.1) — SARIF v2.1.0 output format for `cleanlib`.
//!
//! Emits verdict / scan results as a Static Analysis Results Interchange
//! Format (SARIF) v2.1.0 document — the OASIS standard consumed by
//! GitHub Code Scanning, GitLab MR Security Dashboard, Sonar, and every
//! third-party CI security dashboard that supports SARIF ingest.
//!
//! Spec reference: OASIS SARIF v2.1.0
//! (`https://docs.oasis-open.org/sarif/sarif/v2.1.0/os/sarif-v2.1.0-os.html`)
//! schema: `https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json`
//!
//! Sister-axis with the cycle-7 3-tier decision bucket (`ALLOW` / `WARN` /
//! `DENY`); the SARIF `level` field maps directly onto that bucket
//! (`none` / `warning` / `error`) per the ticket spec. Severity is
//! surfaced as a `properties` bag entry so downstream dashboards can filter
//! independently of the coarse-grained SARIF level.
//!
//! The renderer keeps a *pure* shape — no I/O, no `std::process::exit` —
//! so a golden-file behavioral test can call `verdict_to_sarif` / `decisions_to_sarif`
//! and compare bytes against a fixture.
//!
//! Cross-references CLEANLIB-48 (verdict envelope contract) — the SARIF
//! severity level is derived from the cycle-7 3-tier decision the JSON
//! renderer already computes (`decision_tier_str_with_severity`), so the
//! DENY / WARN / ALLOW mapping stays byte-consistent across text / JSON /
//! SARIF output for the same input.

use serde::{Deserialize, Serialize};

use cleanlib_client::types::{PolicyDecision, Verdict};
use cleanlib_client::CustomerState;

use super::output::decision_tier_str_with_severity;
use super::sanitize::mask_engine_tag;

/// SARIF v2.1.0 canonical schema URI. Consumers (GitHub Code Scanning et al.)
/// key ingest validation off this URI so it MUST match the OASIS-published
/// value exactly.
pub const SARIF_SCHEMA_URI: &str =
    "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json";

/// SARIF v2.1.0 version string carried in the top-level `version` field.
pub const SARIF_VERSION: &str = "2.1.0";

/// Top-level SARIF log envelope — one document per `cleanlib` invocation.
///
/// A SARIF log carries one or more `runs`, each of which describes a single
/// tool execution (`tool.driver`) and its findings (`results`). We always
/// emit a single run per invocation; a scan of N packages surfaces N
/// `results` entries under `runs[0]`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifLog {
    #[serde(rename = "$schema")]
    pub schema: String,
    pub version: String,
    pub runs: Vec<SarifRun>,
}

/// A single tool-execution record. `tool.driver.name` + `.version` identify
/// the emitting binary; `results` carries the finding rows.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifRun {
    pub tool: SarifTool,
    pub results: Vec<SarifResult>,
}

/// Tool identity wrapper. SARIF splits `tool` into `driver` (the primary
/// analyzer) + optional `extensions`; we only populate `driver`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifTool {
    pub driver: SarifDriver,
}

/// Analyzer metadata. `informationUri` points customers back to product
/// docs when a downstream dashboard renders the SARIF run header.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifDriver {
    pub name: String,
    pub version: String,
    #[serde(rename = "informationUri", skip_serializing_if = "Option::is_none")]
    pub information_uri: Option<String>,
}

/// One finding row per package coordinate. `ruleId` is the cleanlib
/// verdict-label (`VECTOR_VERDICT`, `DM_THRESHOLD_BLOCK`, ...);
/// `level` collapses to SARIF's 3-value taxonomy (error / warning / note);
/// `properties` carries the raw cleanlib decision + severity so downstream
/// dashboards can filter without re-mapping.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifResult {
    #[serde(rename = "ruleId")]
    pub rule_id: String,
    pub level: String,
    pub message: SarifMessage,
    pub locations: Vec<SarifLocation>,
    pub properties: SarifResultProperties,
}

/// Human-readable finding text. Only `text` is populated (SARIF also
/// permits `markdown`, but plain text renders identically across every
/// consumer).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifMessage {
    pub text: String,
}

/// Location wrapper. We surface the package coordinate as a
/// `logicalLocations[0]` (SARIF's mechanism for non-file entities such as
/// package identifiers); no `physicalLocation` because dependency
/// findings do not anchor to a source file/line.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifLocation {
    #[serde(rename = "logicalLocations")]
    pub logical_locations: Vec<SarifLogicalLocation>,
}

/// Logical-location entry for a package coordinate.
///
/// `fullyQualifiedName` — canonical `pkg:<ecosystem>/<name>@<version>`
/// (purl-lite shape without the URI escape rules; a full purl RFC-8089
/// build-out is deferred to a follow-up ticket).
/// `kind = "package"` per SARIF §3.33.4 allowed values.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifLogicalLocation {
    pub name: String,
    #[serde(rename = "fullyQualifiedName")]
    pub fully_qualified_name: String,
    pub kind: String,
}

/// SARIF-side `properties` bag. SARIF's `level` is coarse (error/warning/note);
/// customers filtering their Code Scanning views by cleanlib severity need
/// the raw cleanlib decision tier + envelope severity, so we surface both
/// here per SARIF §3.8 property-bag convention.
///
/// CLEANLIB-371 (cycle-18): `state` + `state_label` join the bag. The customer
/// taxonomy in `cleanlib-client::customer_state` is the single source of
/// truth for the 8 customer states; adding it here means a SARIF-consuming
/// dashboard (GitHub Code Scanning, GitLab, Sonar) can filter by the same
/// vocabulary the CLI text renderer + CLI JSON output + SDKs speak.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifResultProperties {
    pub verdict: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub composite_score: Option<u8>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verdict_id: Option<String>,
    /// Snake_case machine string (`CustomerState::as_str`).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub state: String,
    /// Human-readable customer label (`CustomerState::label`).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub state_label: String,
    // ─── CLEANLIB-496 (C1) — attestation parity in SARIF ─────────────────────
    // SARIF `properties` is a conformant free-form bag; surface the same audit +
    // signed-attestation payload as --output json so machine-readable SARIF is
    // signature-verifiable. Omitted (skip None) on v1 / unsigned responses.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audit_record_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audit_record_hash: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attestation: Option<serde_json::Value>,
}

/// Map the cleanlib 3-tier decision (`ALLOW` / `WARN` / `DENY`) to SARIF's
/// `level` enum. SARIF §3.27.10 defines the closed vocab as
/// `none` | `note` | `warning` | `error`; the ticket spec pins
/// `ALLOW → note`, `WARN → warning`, `DENY → error`.
///
/// `note` (not `none`) is used for `ALLOW` because GitHub Code Scanning
/// treats `none`-level entries as informational-only and hides them from
/// the default view — a customer scanning a manifest wants ALLOW rows to
/// remain visible as passing-signal audit evidence.
pub fn decision_to_sarif_level(decision: &str) -> &'static str {
    match decision {
        "ALLOW" => "note",
        "WARN" | "RISK_ACCEPTANCE_REQUIRED" | "INSUFFICIENT_DATA" => "warning",
        "DENY" => "error",
        // Unknown / off-wire — fail loud in the SARIF surface as a warning
        // (matches the cycle-7 fail-closed policy for unknown labels at
        // composite_score < 70).
        _ => "warning",
    }
}

/// Render a single `Verdict` (from `cleanlib verdict`) as a one-result
/// SARIF log.
pub fn verdict_to_sarif(
    verdict: &Verdict,
    ecosystem: &str,
    package: &str,
    version: &str,
    cli_version: &str,
) -> SarifLog {
    let decision = decision_tier_str_with_severity(
        &verdict.verdict,
        verdict.severity.as_deref(),
        verdict.composite_score,
    );
    let level = decision_to_sarif_level(decision).to_string();

    let coord_fqn = format!("pkg:{ecosystem}/{package}@{version}");
    // CLEANLIB-371 (cycle-18): the `message.text` surface is customer-facing
    // (renders into GitHub Code Scanning card headers, GitLab MR side-panels,
    // Sonar rule-description tooltips). Mask engine-tag codenames so
    // `INSUFFICIENT_DATA` / `VECTOR_*` / `DM_*` become their customer labels
    // in the visible text — sister of the CLI text/JSON renderer discipline.
    let masked_verdict_label = mask_engine_tag(&verdict.verdict);
    let message_text = format!(
        "{decision}: {ecosystem}/{package}@{version}{verdict_label}. {reasoning}",
        ecosystem = ecosystem,
        package = package,
        version = version,
        decision = decision,
        verdict_label = masked_verdict_label,
        reasoning = verdict.reasoning,
    );

    // CLEANLIB-371: derive customer-state from wire source (same call the
    // JSON + text renderers make; single source of truth is the canonical
    // taxonomy in `cleanlib-client::customer_state`).
    let state = CustomerState::from_wire(&verdict.source);

    let result = SarifResult {
        // SARIF `ruleId` is a stable machine identifier the dashboard keys
        // reportingDescriptor lookups off — the raw wire label is the right
        // shape here (analogous to CWE-nnn IDs). Human-facing text goes in
        // `message.text` + the customer-state fields in `properties`.
        rule_id: if verdict.verdict.is_empty() {
            "UNKNOWN".to_string()
        } else {
            verdict.verdict.clone()
        },
        level,
        message: SarifMessage {
            text: message_text,
        },
        locations: vec![SarifLocation {
            logical_locations: vec![SarifLogicalLocation {
                name: package.to_string(),
                fully_qualified_name: coord_fqn,
                kind: "package".to_string(),
            }],
        }],
        properties: SarifResultProperties {
            verdict: verdict.verdict.clone(),
            severity: verdict.severity.clone(),
            composite_score: Some(verdict.composite_score),
            verdict_id: if verdict.verdict_id.is_empty() {
                None
            } else {
                Some(verdict.verdict_id.clone())
            },
            state: state.as_str().to_string(),
            state_label: state.label().to_string(),
            // CLEANLIB-496 (C1): audit + attestation passthrough for SARIF parity.
            audit_record_id: verdict.audit_record_id.clone(),
            audit_record_hash: verdict.audit_record_hash.clone(),
            attestation: verdict.attestation.clone(),
        },
    };

    build_log(vec![result], cli_version)
}

/// Render a batch of `PolicyDecision`s (from `cleanlib scan` /
/// `cleanlib policy preview`) as an N-result SARIF log.
pub fn decisions_to_sarif(decisions: &[PolicyDecision], cli_version: &str) -> SarifLog {
    let results = decisions
        .iter()
        .map(|d| policy_decision_to_result(d))
        .collect();
    build_log(results, cli_version)
}

fn policy_decision_to_result(d: &PolicyDecision) -> SarifResult {
    let level = decision_to_sarif_level(&d.decision).to_string();
    let coord_fqn = format!("pkg:{}/{}@{}", d.ecosystem, d.package, d.version);
    // CLEANLIB-371 — mask engine-tag / codename leakage in the message text
    // (SARIF surface — GitHub / GitLab / Sonar consumers).
    let masked_decision = mask_engine_tag(&d.decision);
    let masked_reason = mask_engine_tag(&d.reason);
    let message_text = format!(
        "{}: {}/{}@{}{}",
        masked_decision, d.ecosystem, d.package, d.version, masked_reason
    );
    SarifResult {
        rule_id: if d.decision.is_empty() {
            "UNKNOWN".to_string()
        } else {
            d.decision.clone()
        },
        level,
        message: SarifMessage {
            text: message_text,
        },
        locations: vec![SarifLocation {
            logical_locations: vec![SarifLogicalLocation {
                name: d.package.clone(),
                fully_qualified_name: coord_fqn,
                kind: "package".to_string(),
            }],
        }],
        properties: SarifResultProperties {
            verdict: d.decision.clone(),
            severity: None,
            composite_score: None,
            verdict_id: d.verdict_id.clone(),
            // PolicyDecision has no `source` field to derive customer-state
            // from — omit via the `String::is_empty` skip on the field.
            state: String::new(),
            state_label: String::new(),
            // Scan-path PolicyDecision carries no per-verdict attestation.
            audit_record_id: None,
            audit_record_hash: None,
            attestation: None,
        },
    }
}

fn build_log(results: Vec<SarifResult>, cli_version: &str) -> SarifLog {
    SarifLog {
        schema: SARIF_SCHEMA_URI.to_string(),
        version: SARIF_VERSION.to_string(),
        runs: vec![SarifRun {
            tool: SarifTool {
                driver: SarifDriver {
                    name: "cleanlib".to_string(),
                    version: cli_version.to_string(),
                    information_uri: Some("https://cleanlibrary.clnstrt.dev".to_string()),
                },
            },
            results,
        }],
    }
}

/// Serialize a SARIF log as pretty-printed JSON. Fails only on the
/// unreachable serde-error path (`SarifLog` has no field type that can
/// panic serialize).
pub fn to_json_pretty(log: &SarifLog) -> Result<String, serde_json::Error> {
    serde_json::to_string_pretty(log)
}

/// Convenience helper: render a verdict to SARIF and write to stdout.
/// Sister of `json::render_verdict` (which mirrors this shape for the
/// `--output json` path). Serialisation errors surface via `Result` so
/// the CLI can exit non-zero — the SARIF surface is the one path where a
/// silent-drop would degrade a downstream Code-Scanning ingest.
pub fn print_verdict_sarif(
    verdict: &Verdict,
    ecosystem: &str,
    package: &str,
    version: &str,
    cli_version: &str,
) -> Result<(), serde_json::Error> {
    let log = verdict_to_sarif(verdict, ecosystem, package, version, cli_version);
    println!("{}", to_json_pretty(&log)?);
    Ok(())
}

/// Convenience helper: render a batch of PolicyDecisions to SARIF and
/// write to stdout.
pub fn print_decisions_sarif(
    decisions: &[PolicyDecision],
    cli_version: &str,
) -> Result<(), serde_json::Error> {
    let log = decisions_to_sarif(decisions, cli_version);
    println!("{}", to_json_pretty(&log)?);
    Ok(())
}

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

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

    // ── decision → SARIF level mapping ────────────────────────────────────

    #[test]
    fn allow_maps_to_note() {
        assert_eq!(decision_to_sarif_level("ALLOW"), "note");
    }

    #[test]
    fn warn_maps_to_warning() {
        assert_eq!(decision_to_sarif_level("WARN"), "warning");
    }

    #[test]
    fn deny_maps_to_error() {
        assert_eq!(decision_to_sarif_level("DENY"), "error");
    }

    #[test]
    fn risk_acceptance_required_maps_to_warning() {
        assert_eq!(decision_to_sarif_level("RISK_ACCEPTANCE_REQUIRED"), "warning");
    }

    #[test]
    fn unknown_decision_maps_to_warning_faildown() {
        // Unknown labels default to `warning` — fail-loud on the SARIF
        // surface so a customer's Code Scanning view still shows the row.
        assert_eq!(decision_to_sarif_level("MYSTERY_BAND"), "warning");
    }

    // ── verdict → SARIF envelope shape ────────────────────────────────────

    #[test]
    fn verdict_sarif_has_canonical_schema_and_version() {
        let v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        assert_eq!(log.schema, SARIF_SCHEMA_URI);
        assert_eq!(log.version, "2.1.0");
    }

    #[test]
    fn verdict_sarif_carries_driver_identity() {
        let v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        assert_eq!(log.runs.len(), 1);
        assert_eq!(log.runs[0].tool.driver.name, "cleanlib");
        assert_eq!(log.runs[0].tool.driver.version, "0.1.4");
    }

    #[test]
    fn verdict_sarif_emits_one_result_per_verdict() {
        let v = make_verdict("VECTOR_VERDICT", 85);
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        assert_eq!(log.runs[0].results.len(), 1);
    }

    #[test]
    fn verdict_sarif_result_rule_id_matches_verdict_label() {
        let v = make_verdict("DM_THRESHOLD_BLOCK", 90);
        let log = verdict_to_sarif(&v, "npm", "malicious-pkg", "1.0.0", "0.1.4");
        assert_eq!(log.runs[0].results[0].rule_id, "DM_THRESHOLD_BLOCK");
    }

    #[test]
    fn verdict_sarif_deny_maps_result_level_to_error() {
        let v = make_verdict("DM_THRESHOLD_BLOCK", 90);
        let log = verdict_to_sarif(&v, "npm", "malicious-pkg", "1.0.0", "0.1.4");
        assert_eq!(log.runs[0].results[0].level, "error");
    }

    #[test]
    fn verdict_sarif_allow_maps_result_level_to_note() {
        let v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        assert_eq!(log.runs[0].results[0].level, "note");
    }

    #[test]
    fn verdict_sarif_vector_high_sev_maps_to_error() {
        // VECTOR_VERDICT + severity HIGH → DENY → error (CLEANLIB-270).
        let mut v = make_verdict("VECTOR_VERDICT", 85);
        v.severity = Some("HIGH".to_string());
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        assert_eq!(log.runs[0].results[0].level, "error");
    }

    #[test]
    fn verdict_sarif_vector_medium_sev_maps_to_warning() {
        // VECTOR_VERDICT + severity MEDIUM → WARN → warning.
        let mut v = make_verdict("VECTOR_VERDICT", 85);
        v.severity = Some("MEDIUM".to_string());
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        assert_eq!(log.runs[0].results[0].level, "warning");
    }

    // ── location shape (package coordinate as logicalLocation) ────────────

    #[test]
    fn verdict_sarif_locations_carry_package_coordinate() {
        let v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        let loc = &log.runs[0].results[0].locations[0].logical_locations[0];
        assert_eq!(loc.name, "cors");
        assert_eq!(loc.fully_qualified_name, "pkg:npm/cors@2.8.5");
        assert_eq!(loc.kind, "package");
    }

    // ── properties bag carries raw cleanlib metadata ──────────────────────

    #[test]
    fn verdict_sarif_properties_carry_severity_and_composite_score() {
        let mut v = make_verdict("VECTOR_VERDICT", 85);
        v.severity = Some("HIGH".to_string());
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        let props = &log.runs[0].results[0].properties;
        assert_eq!(props.verdict, "VECTOR_VERDICT");
        assert_eq!(props.severity.as_deref(), Some("HIGH"));
        assert_eq!(props.composite_score, Some(85));
        assert_eq!(props.verdict_id.as_deref(), Some("vrd-test-001"));
    }

    // ── PolicyDecision batch shape ────────────────────────────────────────

    fn make_pd(name: &str, version: &str, decision: &str) -> PolicyDecision {
        PolicyDecision {
            ecosystem: "npm".to_string(),
            package: name.to_string(),
            version: version.to_string(),
            decision: decision.to_string(),
            reason: format!("test-reason-{decision}"),
            verdict_id: Some(format!("vrd-{name}")),
            policy_rule_id: None,
        }
    }

    #[test]
    fn decisions_sarif_emits_one_result_per_decision() {
        let decisions = vec![
            make_pd("cors", "2.8.5", "ALLOW"),
            make_pd("malicious-pkg", "1.0.0", "DENY"),
            make_pd("stale-pkg", "0.9.0", "WARN"),
        ];
        let log = decisions_to_sarif(&decisions, "0.1.4");
        assert_eq!(log.runs[0].results.len(), 3);
    }

    #[test]
    fn decisions_sarif_levels_match_decisions() {
        let decisions = vec![
            make_pd("cors", "2.8.5", "ALLOW"),
            make_pd("malicious-pkg", "1.0.0", "DENY"),
            make_pd("stale-pkg", "0.9.0", "WARN"),
        ];
        let log = decisions_to_sarif(&decisions, "0.1.4");
        let levels: Vec<&str> = log.runs[0]
            .results
            .iter()
            .map(|r| r.level.as_str())
            .collect();
        assert_eq!(levels, vec!["note", "error", "warning"]);
    }

    // ── SARIF v2.1.0 schema-conformance smoke ─────────────────────────────
    //
    // Full schema-conformance is exercised by the integration golden test
    // (tests/integration/sarif_golden.rs); this in-crate smoke asserts the
    // structural invariants that make a SARIF document valid at the
    // OASIS-spec level.

    #[test]
    fn sarif_top_level_shape_conforms_to_v210() {
        let v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        let value = serde_json::to_value(&log).unwrap();

        // SARIF §3.1: required keys on the log envelope.
        assert!(value.get("$schema").is_some(), "$schema is required");
        assert!(value.get("version").is_some(), "version is required");
        assert!(value.get("runs").is_some(), "runs is required");
        assert_eq!(value["version"], "2.1.0");

        // SARIF §3.14: required keys on a run.
        let run = &value["runs"][0];
        assert!(run.get("tool").is_some(), "run.tool is required");
        assert!(run.get("results").is_some(), "run.results is required");

        // SARIF §3.18: required keys on tool.
        let tool = &run["tool"];
        assert!(tool.get("driver").is_some(), "tool.driver is required");

        // SARIF §3.19: required keys on toolComponent (driver).
        let driver = &tool["driver"];
        assert!(driver.get("name").is_some(), "driver.name is required");
    }

    #[test]
    fn sarif_result_shape_conforms_to_v210() {
        let v = make_verdict("VECTOR_VERDICT", 85);
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        let value = serde_json::to_value(&log).unwrap();

        // SARIF §3.27: required keys on a result.
        let result = &value["runs"][0]["results"][0];
        assert!(result.get("ruleId").is_some(), "result.ruleId is expected");
        assert!(result.get("level").is_some(), "result.level is expected");
        assert!(result.get("message").is_some(), "result.message is required");

        // SARIF §3.11: message MUST have `text` OR `markdown`.
        let msg = &result["message"];
        assert!(msg.get("text").is_some(), "message.text is required");

        // SARIF §3.27.10: level MUST be one of the closed vocab.
        let level = result["level"].as_str().unwrap();
        assert!(
            matches!(level, "none" | "note" | "warning" | "error"),
            "level must be one of SARIF's closed vocab; got {level}"
        );
    }

    #[test]
    fn sarif_empty_decisions_still_produces_valid_run() {
        // Zero-finding scans (all packages ALLOW-filtered out earlier)
        // must still emit a well-formed SARIF envelope; downstream Code
        // Scanning re-uploads treat an empty results array as
        // "previously-flagged findings resolved".
        let log = decisions_to_sarif(&[], "0.1.4");
        assert_eq!(log.runs[0].results.len(), 0);
        // Serialization must still succeed.
        let s = to_json_pretty(&log).unwrap();
        assert!(s.contains("\"version\": \"2.1.0\""));
        assert!(s.contains("\"results\": []"));
    }

    // ── CLEANLIB-371 (cycle-18) — canonical customer-state on SARIF ───────
    //
    // The SARIF properties bag now carries the canonical customer-state
    // (snake_case machine key + human label) so a Code Scanning / GitLab /
    // Sonar dashboard can filter + display consistently with the CLI text
    // renderer, CLI JSON output, and SDKs.

    #[test]
    fn verdict_sarif_properties_carry_state_and_state_label() {
        let mut v = make_verdict("VECTOR_VERDICT", 85);
        v.source = "CVE_FINDING_ON_KEV".to_string();
        v.severity = Some("HIGH".to_string());
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        let value = serde_json::to_value(&log).unwrap();
        let props = &value["runs"][0]["results"][0]["properties"];
        assert_eq!(props["state"], "actively_exploited");
        assert_eq!(props["state_label"], "Actively exploited");
    }

    #[test]
    fn verdict_sarif_properties_carry_not_yet_assessed_for_insufficient_data() {
        // CLEANLIB-371 root repro: `INSUFFICIENT_DATA` used to leak as raw
        // codename in every SARIF-emit path; now the state field carries the
        // customer-facing label + machine string via `CustomerState`.
        let mut v = make_verdict("INSUFFICIENT_DATA", 30);
        v.source = "INSUFFICIENT_DATA".to_string();
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        let value = serde_json::to_value(&log).unwrap();
        let props = &value["runs"][0]["results"][0]["properties"];
        assert_eq!(props["state"], "not_yet_assessed");
        assert_eq!(props["state_label"], "Not yet assessed");
    }

    #[test]
    fn verdict_sarif_message_masks_insufficient_data_codename() {
        // The `message.text` surface renders in dashboards. It must not
        // carry the raw `INSUFFICIENT_DATA` wire codename — masked to
        // "Not yet assessed" (matches the CLI text + JSON output).
        let mut v = make_verdict("INSUFFICIENT_DATA", 30);
        v.source = "INSUFFICIENT_DATA".to_string();
        v.reasoning = "no fresh evidence".to_string();
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        let text = &log.runs[0].results[0].message.text;
        assert!(
            !text.contains("INSUFFICIENT_DATA"),
            "SARIF message.text leaked raw codename: {}",
            text
        );
        assert!(
            text.contains("Not yet assessed"),
            "SARIF message.text missing canonical customer label: {}",
            text
        );
    }

    #[test]
    fn decisions_sarif_state_fields_omit_when_no_source() {
        // PolicyDecision has no `source` field to derive customer-state
        // from; the SARIF-side state fields must skip-serialize rather than
        // land as empty strings in the JSON output.
        let pd = PolicyDecision {
            ecosystem: "npm".to_string(),
            package: "cors".to_string(),
            version: "2.8.5".to_string(),
            decision: "ALLOW".to_string(),
            reason: "no findings".to_string(),
            verdict_id: Some("vrd-1".to_string()),
            policy_rule_id: None,
        };
        let log = decisions_to_sarif(&[pd], "0.1.4");
        let value = serde_json::to_value(&log).unwrap();
        let props = &value["runs"][0]["results"][0]["properties"];
        assert!(
            props.get("state").is_none(),
            "state must be omitted when PolicyDecision carries no source"
        );
        assert!(
            props.get("state_label").is_none(),
            "state_label must be omitted when PolicyDecision carries no source"
        );
    }

    // ── verdict_id omission when empty ────────────────────────────────────

    #[test]
    fn verdict_sarif_omits_verdict_id_when_empty() {
        let mut v = make_verdict("ALLOWED_NO_FINDINGS", 30);
        v.verdict_id = String::new();
        let log = verdict_to_sarif(&v, "npm", "cors", "2.8.5", "0.1.4");
        let value = serde_json::to_value(&log).unwrap();
        let props = &value["runs"][0]["results"][0]["properties"];
        assert!(
            props.get("verdict_id").is_none(),
            "verdict_id must be omitted when empty (not serialized as empty string)"
        );
    }
}