cleanlib-cli 0.1.4

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
//! `cleanlib scan` (cycle-7 Cli2). Migrates `cmd_scan` from `main.rs`.

use std::path::{Path, PathBuf};

use anyhow::Result;
use cleanlib_client::{config, transport, types};
use crate::render::sarif;
use crate::render::terminal;

use super::scan_exit_code;

/// CLI version threaded into SARIF `tool.driver.version`. Sourced from
/// Cargo at compile time (see also `commands::verdict::CLI_VERSION`).
const CLI_VERSION: &str = env!("CARGO_PKG_VERSION");

pub async fn run(ecosystem: String, packages_path: PathBuf, output: String) -> Result<()> {
    let path = config::default_path();
    let cfg = config::load_with_env_overrides(path.as_deref())?;
    let client = transport::Client::from_config(&cfg)?;

    // CLEANLIB-364 / CLEANLIB-367 — ecosystem-filter on a mixed-eco packages
    // file. The customer-facing invariant is that `--ecosystem npm` sends ONLY
    // npm-shape packages to `/v1/scan` and surfaces ONLY npm verdicts, with a
    // loud stderr warning listing every entry that got dropped so the audit
    // trail explains any decision-count delta vs. the raw lockfile.
    // Reject empty --ecosystem flag
    if ecosystem.trim().is_empty() {
        let supported = client.get_ecosystems().await.unwrap_or_else(|_| {
            vec!["npm".to_string(), "pypi".to_string(), "go".to_string(),
                 "crates".to_string(), "maven".to_string(), "nuget".to_string(),
                 "rubygems".to_string(), "composer".to_string()]
        });
        anyhow::bail!(
            "empty --ecosystem '{}' requires at least one value (e.g. --ecosystem=npm).\n       Supported ecosystems: {}",
            ecosystem,
            supported.join(", ")
        );
    }
    // Validate ecosystem names against server-supported list from GET /health
    let eco_filter = parse_ecosystem_filter(&ecosystem);
    let supported_ecosystems = client.get_ecosystems().await.unwrap_or_else(|_| {
        vec![
            "npm".to_string(), "pypi".to_string(), "go".to_string(),
            "crates".to_string(), "maven".to_string(), "nuget".to_string(),
            "rubygems".to_string(), "composer".to_string(),
        ]
    });
    let unknown: Vec<&str> = eco_filter
        .iter()
        .filter(|e| !supported_ecosystems.contains(e))
        .map(|s| s.as_str())
        .collect();
    if !unknown.is_empty() {
        anyhow::bail!(
            "unknown ecosystem(s): {} — supported ecosystems: {}",
            unknown.join(", "),
            supported_ecosystems.join(", ")
        );
    }
    let parsed = parse_packages_file(&packages_path, &ecosystem)?;
    warn_filtered_inputs(&ecosystem, &parsed.filtered_out);
    let packages = parsed.packages;
    // Friendly error if no packages found for requested ecosystem
    if packages.is_empty() {
        eprintln!(
            "WARN: no packages found for ecosystem '{}' in {}",
            ecosystem,
            packages_path.display()
        );
        eprintln!(
            "      Check that your packages file has entries under a '# {}' section header,",
            ecosystem
        );
        eprintln!(
            "      or that JSON entries declare ecosystem field in each entry.",
        );
        std::process::exit(2);
    }
    let requested = packages.len();
    // `cleanlib scan` previews packages against the customer's active policy
    // via `POST /v1/scan` (verdict-driven), NOT `/v1/policy/preview` (which
    // requires a candidate `policy_yaml` — that's `cleanlib policy preview`).
    let req = types::ScanRequest { packages };
    let resp = client.scan(&req).await?;

    // Fail-loud on a silent empty gate: a non-empty request that comes back
    // with zero results means the scan decided nothing, so exiting 0 would be
    // a fail-open. This is the close of the old `PolicyPreviewResponse`
    // (`{decisions}`, serde-default) bug, which parsed the App's `{results}`
    // body into an empty vec and passed CI silently.
    if requested > 0 && resp.results.is_empty() {
        anyhow::bail!(
            "scan returned no results for {} requested package(s) — refusing to \
             report a passing gate on an empty response",
            requested
        );
    }

    // CLEANLIB-364 / CLEANLIB-367 — defensive response-side filter. Even
    // after we scrub the request, a server-side bug (or a legacy cached
    // response replayed by an intermediary) could return verdicts for
    // ecosystems we never asked about. Drop them and warn — never let
    // cross-eco verdicts leak into the gate.
    let (kept_results, dropped_results) =
        partition_results_by_ecosystem(resp.results, &ecosystem);
    warn_filtered_response(&ecosystem, &dropped_results);

    // The App returns a resolved verdict per package (no pre-computed policy
    // decision on the scan path), so derive the gating decision per result and
    // render/aggregate through the shared `PolicyDecision` surface.
    let decisions: Vec<types::PolicyDecision> =
        kept_results.iter().map(decision_from_result).collect();

    match output.as_str() {
        "json" => println!("{}", serde_json::to_string_pretty(&decisions)?),
        // CLEANLIB-196 (Client-3.1) — SARIF v2.1.0 batch output. One
        // SARIF `result` per PolicyDecision so a `cleanlib scan` of an
        // N-package manifest produces an N-result SARIF log ready for
        // GitHub Code Scanning upload.
        "sarif" => {
            sarif::print_decisions_sarif(&decisions, CLI_VERSION)
                .map_err(|e| anyhow::anyhow!("failed to serialise SARIF: {e}"))?;
        }
        _ => terminal::render_decisions(&decisions),
    }

    let code = scan_exit_code(&decisions);
    if code != 0 {
        std::process::exit(code);
    }
    Ok(())
}

/// Derive a gating [`types::PolicyDecision`] from one `/v1/scan` result.
///
/// `scan` is verdict-driven — the App returns the resolved verdict, not a
/// pre-computed policy decision — so we take the raw decision string
/// (preferring the explicit `verdict.decision` from Lane-2 M1, falling back to
/// the `verdict.verdict` label) and normalize it through the shared
/// `normalize_decision` so the `decision` field holds the canonical gate
/// outcome (ALLOW / DENY / WARN / RISK_ACCEPTANCE_REQUIRED) rather than a raw
/// engine label. This is what both the table renderer and `--output json`
/// surface: pre-normalization a `DM_THRESHOLD_BLOCK` label reached the
/// renderer's `mask_engine_tag` and displayed as "Policy decision" instead of
/// DENY. The raw label/reasoning is preserved in `reason`. `scan_exit_code`
/// re-applies `normalize_decision` (idempotent) so the exit-code contract is
/// unchanged. A per-package `error` (the App's partial-success miss) maps to
/// INSUFFICIENT_DATA → WARN so the gate warns loudly rather than passing
/// silently.
fn decision_from_result(r: &types::ScanResult) -> types::PolicyDecision {
    let (raw_decision, reason, verdict_id) = match (&r.verdict, &r.error) {
        (Some(v), _) => (
            v.decision.clone().unwrap_or_else(|| v.verdict.clone()),
            v.reasoning.clone(),
            Some(v.verdict_id.clone()),
        ),
        (None, Some(e)) => ("INSUFFICIENT_DATA".to_string(), format!("scan error: {e}"), None),
        (None, None) => (
            "INSUFFICIENT_DATA".to_string(),
            "no verdict returned".to_string(),
            None,
        ),
    };
    types::PolicyDecision {
        ecosystem: r.ecosystem.clone(),
        package: r.package.clone(),
        version: r.version.clone(),
        decision: super::normalize_decision(&raw_decision).to_string(),
        reason,
        verdict_id,
        policy_rule_id: None,
    }
}

/// One packages-file entry that was dropped because its declared ecosystem
/// did not match the CLI's `--ecosystem` filter. Carried on
/// [`ParsedPackages::filtered_out`] so the caller can surface a per-entry
/// audit-trail warning (CLEANLIB-364 / CLEANLIB-367).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilteredEntry {
    /// The ecosystem the packages-file entry declared for itself
    /// (e.g. `"pypi"` when the file was scanned with `--ecosystem npm`).
    pub declared_ecosystem: String,
    pub name: String,
    pub version: String,
}

/// Result of parsing a packages file with an `--ecosystem` filter applied.
///
/// `packages` are the entries kept (ecosystem matches, or ecosystem was
/// unspecified in the source and defaulted to the CLI flag). `filtered_out`
/// carries every entry whose source-declared ecosystem did not match, so the
/// scan/policy-preview surfaces can warn loudly rather than silently
/// dropping cross-eco lines from a mixed lockfile.
#[derive(Debug, Clone, Default)]
pub struct ParsedPackages {
    pub packages: Vec<types::PackageRef>,
    pub filtered_out: Vec<FilteredEntry>,
}

/// Parse a packages file. Accepts two formats — auto-detected from the
/// first non-whitespace character:
///
/// 1. **JSON array** (when the file starts with `[`) — each element is
///    `{"name": "...", "version": "..."}` with an optional `"ecosystem"`
///    field. Cycle-14 DX-fix: a common customer-facing shape (e.g., output
///    of `npm ls --json | jq ...`) that the text-only parser previously
///    rejected. CLEANLIB-364 / CLEANLIB-367: when an entry declares its own
///    `ecosystem` and it does not match `ecosystem`, the entry is dropped
///    into [`ParsedPackages::filtered_out`] so the caller can warn.
///
/// 2. **Plain text** (default) — one `name@version` per line; `#`-prefix
///    lines and blank lines ignored. Text lines have no self-declared
///    ecosystem and always inherit the CLI-requested `ecosystem`.
///
/// Returns [`ParsedPackages`] or an error pointing at the first malformed
/// line (text) or a JSON parse error (array).
/// Parse a comma-separated ecosystem filter into a list.
/// "npm" -> ["npm"], "npm,go,pypi" -> ["npm", "go", "pypi"]
pub fn parse_ecosystem_filter(ecosystem: &str) -> Vec<String> {
    ecosystem
        .split(',')
        .map(|s| s.trim().to_lowercase())
        .filter(|s| !s.is_empty())
        .collect()
}

/// Known ecosystem header names for txt file # section detection.
/// ONLY for recognizing section headers — NOT for validation.
/// Validation uses server-side list from GET /health.
const ECOSYSTEM_HEADERS: &[&str] = &[
    "npm", "pypi", "go", "crates", "maven", "nuget", "rubygems", "composer",
];

fn parse_ecosystem_header(line: &str) -> Option<String> {
    let body = line.trim_start_matches('#').trim().to_lowercase();
    let first_word = body.split_whitespace().next()?;
    if ECOSYSTEM_HEADERS.contains(&first_word) {
        Some(first_word.to_string())
    } else {
        None
    }
}

pub fn parse_packages_file(path: &Path, ecosystem: &str) -> Result<ParsedPackages> {
    let content = std::fs::read_to_string(path)
        .map_err(|e| anyhow::anyhow!("read {}: {}", path.display(), e))?;
    if content.trim_start().starts_with('[') {
        return parse_packages_json_array(&content, path, ecosystem);
    }
    let requested = parse_ecosystem_filter(ecosystem);
    let mut packages = Vec::new();
    let mut filtered_out = Vec::new();
    let mut current_section_eco: Option<String> = None;
    for (lineno, raw_line) in content.lines().enumerate() {
        let line = raw_line.trim();
        if line.is_empty() {
            continue;
        }
        if line.starts_with('#') {
            if let Some(eco) = parse_ecosystem_header(line) {
                current_section_eco = Some(eco);
            }
            continue;
        }
        let (name, version) = match line.rsplit_once('@') {
            Some((n, v)) if !n.is_empty() && !v.is_empty() => (n.to_string(), v.to_string()),
            _ => anyhow::bail!(
                "{}:{}: malformed packages-file line (expected `name@version`): {}",
                path.display(),
                lineno + 1,
                line
            ),
        };
        let line_eco = current_section_eco
            .clone()
            .unwrap_or_else(|| requested[0].clone());
        if requested.contains(&line_eco) {
            packages.push(types::PackageRef {
                ecosystem: line_eco,
                name,
                version,
            });
        } else {
            filtered_out.push(FilteredEntry {
                declared_ecosystem: line_eco,
                name,
                version,
            });
        }
    }
    Ok(ParsedPackages {
        packages,
        filtered_out,
    })
}

#[derive(serde::Deserialize)]
struct PackagesJsonEntry {
    name: String,
    version: String,
    /// Optional per-entry ecosystem — set by mixed-lockfile exports
    /// (e.g. `[{"ecosystem":"npm",...},{"ecosystem":"pypi",...}]`).
    /// Missing/absent means "inherit the CLI --ecosystem flag".
    #[serde(default)]
    ecosystem: Option<String>,
}

fn parse_packages_json_array(
    content: &str,
    path: &Path,
    ecosystem: &str,
) -> Result<ParsedPackages> {
    let entries: Vec<PackagesJsonEntry> = serde_json::from_str(content).map_err(|e| {
        anyhow::anyhow!(
            "{}: failed to parse JSON-array packages file (expected `[{{\"name\":\"...\",\"version\":\"...\"}},...]`): {}",
            path.display(),
            e
        )
    })?;
    let requested = parse_ecosystem_filter(ecosystem);
    let mut packages = Vec::new();
    let mut filtered_out = Vec::new();
    for e in entries {
        if let Some(declared) = e.ecosystem.as_deref() {
            let declared_lower = declared.to_lowercase();
            if !requested.contains(&declared_lower) {
                filtered_out.push(FilteredEntry {
                    declared_ecosystem: declared.to_string(),
                    name: e.name,
                    version: e.version,
                });
                continue;
            }
            packages.push(types::PackageRef {
                ecosystem: declared_lower,
                name: e.name,
                version: e.version,
            });
        } else {
            packages.push(types::PackageRef {
                ecosystem: requested[0].clone(),
                name: e.name,
                version: e.version,
            });
        }
    }
    Ok(ParsedPackages {
        packages,
        filtered_out,
    })
}

/// Partition scan results into `(kept, dropped)` by matching the response
/// `ecosystem` field against the requested one. Defensive counterpart to
/// the input-side filter: even after we scrub the request, a stale/mis-routed
/// response must not leak cross-eco verdicts into the gate.
///
/// An empty `ecosystem` on the result is treated as a match (older App
/// builds omit the field; refusing them here would be a self-inflicted
/// regression on the fail-loud-on-empty-response contract in `run`).
pub(crate) fn partition_results_by_ecosystem(
    results: Vec<types::ScanResult>,
    ecosystem: &str,
) -> (Vec<types::ScanResult>, Vec<types::ScanResult>) {
    let requested = parse_ecosystem_filter(ecosystem);
    let mut kept = Vec::with_capacity(results.len());
    let mut dropped = Vec::new();
    for r in results {
        if r.ecosystem.is_empty() || requested.contains(&r.ecosystem.to_lowercase()) {
            kept.push(r);
        } else {
            dropped.push(r);
        }
    }
    (kept, dropped)
}

/// Emit a stderr audit-trail warning listing every packages-file entry that
/// was dropped by the `--ecosystem` filter. No-op when nothing was filtered
/// so the happy-path stays quiet.
fn warn_filtered_inputs(ecosystem: &str, filtered: &[FilteredEntry]) {
    if filtered.is_empty() {
        return;
    }
    eprintln!(
        "warning: --ecosystem {} filtered {} packages-file entr{} of a different ecosystem:",
        ecosystem,
        filtered.len(),
        if filtered.len() == 1 { "y" } else { "ies" },
    );
    for f in filtered {
        eprintln!(
            "  - {}@{} (declared ecosystem: {})",
            f.name, f.version, f.declared_ecosystem,
        );
    }
}

/// Sister of [`warn_filtered_inputs`] for the response-side defensive filter.
fn warn_filtered_response(ecosystem: &str, dropped: &[types::ScanResult]) {
    if dropped.is_empty() {
        return;
    }
    eprintln!(
        "warning: --ecosystem {} dropped {} scan result{} returned for a different ecosystem:",
        ecosystem,
        dropped.len(),
        if dropped.len() == 1 { "" } else { "s" },
    );
    for r in dropped {
        eprintln!(
            "  - {}@{} (response ecosystem: {})",
            r.package, r.version, r.ecosystem,
        );
    }
}

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

    // Process-wide monotonic counter so parallel tests never collide on a temp
    // filename. The previous nanosecond-timestamp scheme could produce identical
    // names when two tests ran in the same clock tick (coarse-resolution
    // platforms), letting one test clobber another's file mid-read — the source
    // of the intermittent `parses_json_array_input` failure under parallel runs.
    static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

    fn tmp_packages_file(contents: &str) -> PathBuf {
        let dir = std::env::temp_dir();
        let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let path = dir.join(format!(
            "cleanlib-scan-test-{}-{}-{}.txt",
            std::process::id(),
            seq,
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::write(&path, contents).unwrap();
        path
    }

    #[test]
    fn parses_simple() {
        let p = tmp_packages_file("lodash@4.17.21\ncors@2.8.5\n");
        let parsed = parse_packages_file(&p, "npm").unwrap();
        assert_eq!(parsed.packages.len(), 2);
        assert_eq!(parsed.packages[0].name, "lodash");
        assert_eq!(parsed.packages[0].version, "4.17.21");
        assert!(parsed.filtered_out.is_empty());
        let _ = std::fs::remove_file(&p);
    }

    #[test]
    fn skips_comments_and_blank() {
        let p = tmp_packages_file("# header\n\ncors@2.8.5\n# trailer\n");
        let parsed = parse_packages_file(&p, "npm").unwrap();
        assert_eq!(parsed.packages.len(), 1);
        let _ = std::fs::remove_file(&p);
    }

    #[test]
    fn malformed_line_errors() {
        let p = tmp_packages_file("invalid-no-at-sign\n");
        let err = parse_packages_file(&p, "npm").unwrap_err();
        assert!(err.to_string().contains("malformed"));
        let _ = std::fs::remove_file(&p);
    }

    #[test]
    fn parses_json_array_input() {
        // Cycle-14 DX-fix: customers commonly produce package lists via
        // tools that emit JSON (e.g., `npm ls --json | jq ...`). The
        // parser auto-detects a leading `[` and uses JSON-array parsing.
        let p = tmp_packages_file(
            r#"[
  {"name": "lodash", "version": "4.17.21"},
  {"name": "express", "version": "4.18.2"}
]"#,
        );
        let parsed = parse_packages_file(&p, "npm").unwrap();
        assert_eq!(parsed.packages.len(), 2);
        assert_eq!(parsed.packages[0].name, "lodash");
        assert_eq!(parsed.packages[0].version, "4.17.21");
        assert_eq!(parsed.packages[1].name, "express");
        assert_eq!(parsed.packages[1].ecosystem, "npm");
        assert!(parsed.filtered_out.is_empty());
        let _ = std::fs::remove_file(&p);
    }

    #[test]
    fn json_array_with_invalid_shape_reports_clean_error() {
        let p = tmp_packages_file(r#"[{"name": "lodash"}]"#); // missing version
        let err = parse_packages_file(&p, "npm").unwrap_err();
        assert!(
            err.to_string().contains("parse JSON-array")
                || err.to_string().contains("missing field"),
            "expected JSON parse error; got: {}",
            err
        );
        let _ = std::fs::remove_file(&p);
    }

    // ── CLEANLIB-364 / CLEANLIB-367 — ecosystem-filter on mixed lockfiles ─
    // A JSON-array packages file that declares per-entry `ecosystem` must
    // (a) send ONLY entries matching --ecosystem to the App, (b) surface every
    // dropped entry on `filtered_out` so the caller can warn (audit trail),
    // and (c) leave the response-side defensive filter drop any cross-eco
    // verdicts a mis-routed server could otherwise leak into the gate.

    #[test]
    fn mixed_ecosystem_json_filters_to_requested_ecosystem() {
        let p = tmp_packages_file(
            r#"[
  {"ecosystem": "npm",  "name": "lodash",   "version": "4.17.21"},
  {"ecosystem": "npm",  "name": "express",  "version": "4.18.2"},
  {"ecosystem": "pypi", "name": "requests", "version": "2.31.0"},
  {"ecosystem": "pypi", "name": "urllib3",  "version": "2.0.7"}
]"#,
        );
        let parsed = parse_packages_file(&p, "npm").unwrap();

        // Only the npm-shape entries reach the request payload; every kept
        // entry carries the requested ecosystem on the wire.
        assert_eq!(parsed.packages.len(), 2, "expected 2 npm packages kept");
        assert!(parsed.packages.iter().all(|pk| pk.ecosystem == "npm"));
        assert!(parsed.packages.iter().any(|pk| pk.name == "lodash"));
        assert!(parsed.packages.iter().any(|pk| pk.name == "express"));

        // Both non-npm entries land on `filtered_out` with their declared
        // ecosystem preserved for the audit-trail warning.
        assert_eq!(
            parsed.filtered_out.len(),
            2,
            "expected 2 pypi entries filtered out"
        );
        assert!(parsed
            .filtered_out
            .iter()
            .all(|f| f.declared_ecosystem == "pypi"));
        assert!(parsed.filtered_out.iter().any(|f| f.name == "requests"));
        assert!(parsed.filtered_out.iter().any(|f| f.name == "urllib3"));

        let _ = std::fs::remove_file(&p);
    }

    #[test]
    fn mixed_ecosystem_response_partition_drops_cross_eco_verdicts() {
        // Simulates the App handing back verdicts for a mixed batch —
        // defensively drop the pypi row so only npm decisions surface to the
        // renderer / exit-code gate, and expose the dropped row for the
        // warn-and-audit stderr line.
        let results = vec![
            types::ScanResult {
                ecosystem: "npm".to_string(),
                package: "lodash".to_string(),
                version: "4.17.21".to_string(),
                verdict: Some(verdict_label("ALLOW")),
                error: None,
            },
            types::ScanResult {
                ecosystem: "pypi".to_string(),
                package: "requests".to_string(),
                version: "2.31.0".to_string(),
                verdict: Some(verdict_label("DENY")),
                error: None,
            },
            types::ScanResult {
                ecosystem: "npm".to_string(),
                package: "express".to_string(),
                version: "4.18.2".to_string(),
                verdict: Some(verdict_label("ALLOW")),
                error: None,
            },
        ];

        let (kept, dropped) = partition_results_by_ecosystem(results, "npm");
        assert_eq!(kept.len(), 2);
        assert!(kept.iter().all(|r| r.ecosystem == "npm"));
        assert_eq!(dropped.len(), 1);
        assert_eq!(dropped[0].package, "requests");
        assert_eq!(dropped[0].ecosystem, "pypi");
    }

    #[test]
    fn response_partition_keeps_results_with_empty_ecosystem_field() {
        // Older App builds serialize `ecosystem` as an empty string when
        // omitted; keeping them matches the current fail-loud-on-empty-response
        // contract in `run`. Defensive filter must not double-punish.
        let results = vec![types::ScanResult {
            ecosystem: String::new(),
            package: "lodash".to_string(),
            version: "4.17.21".to_string(),
            verdict: Some(verdict_label("ALLOW")),
            error: None,
        }];
        let (kept, dropped) = partition_results_by_ecosystem(results, "npm");
        assert_eq!(kept.len(), 1);
        assert!(dropped.is_empty());
    }

    #[test]
    fn json_entry_without_declared_ecosystem_inherits_cli_flag() {
        // No per-entry ecosystem → treat as matching (legacy shape); the CLI
        // --ecosystem is stamped onto the wire coordinate.
        let p = tmp_packages_file(
            r#"[
  {"name": "lodash", "version": "4.17.21"}
]"#,
        );
        let parsed = parse_packages_file(&p, "npm").unwrap();
        assert_eq!(parsed.packages.len(), 1);
        assert_eq!(parsed.packages[0].ecosystem, "npm");
        assert!(parsed.filtered_out.is_empty());
        let _ = std::fs::remove_file(&p);
    }

    // ── decision_from_result: /v1/scan verdict → gating decision ────────────
    // Guards the verdict-driven derivation on the scan path + the fail-loud
    // treatment of a per-package error (App partial-success miss). Pair with
    // `super::scan_exit_code`'s `normalize_decision` tests in commands::mod.

    fn scan_result(verdict: Option<types::Verdict>, error: Option<String>) -> types::ScanResult {
        types::ScanResult {
            ecosystem: "pypi".to_string(),
            package: "requests".to_string(),
            version: "2.32.5".to_string(),
            verdict,
            error,
        }
    }

    fn verdict_label(label: &str) -> types::Verdict {
        types::Verdict {
            verdict_id: "vrd-scan-001".to_string(),
            verdict: label.to_string(),
            ..types::Verdict::default()
        }
    }

    #[test]
    fn decision_prefers_explicit_verdict_decision() {
        let mut v = verdict_label("VECTOR_VERDICT");
        v.decision = Some("DENY".to_string());
        let d = decision_from_result(&scan_result(Some(v), None));
        assert_eq!(d.decision, "DENY");
        assert_eq!(d.package, "requests");
        assert_eq!(d.verdict_id.as_deref(), Some("vrd-scan-001"));
    }

    #[test]
    fn decision_falls_back_to_verdict_label_then_normalizes() {
        // No explicit decision → fall back to the raw label, then normalize:
        // INSUFFICIENT_DATA → WARN (fail-loud). The canonical outcome is what
        // reaches the renderer + JSON `decision` field.
        let d = decision_from_result(&scan_result(Some(verdict_label("INSUFFICIENT_DATA")), None));
        assert_eq!(d.decision, "WARN");
        assert_eq!(super::super::scan_exit_code(std::slice::from_ref(&d)), 2);
    }

    #[test]
    fn decision_block_label_normalizes_to_deny() {
        // CLEANLIB fix: a block-equivalent engine label must surface as the
        // canonical DENY in `decision` (was leaking the raw DM_THRESHOLD_BLOCK
        // label, which the table renderer masked to "Policy decision").
        let d = decision_from_result(&scan_result(Some(verdict_label("DM_THRESHOLD_BLOCK")), None));
        assert_eq!(d.decision, "DENY");
        assert_eq!(super::super::scan_exit_code(std::slice::from_ref(&d)), 1);
    }

    #[test]
    fn decision_error_result_is_fail_loud_warn_not_silent_allow() {
        // A per-package scan error must NOT silently pass the gate. Raw
        // INSUFFICIENT_DATA normalizes to WARN; the raw reasoning stays in
        // `reason`.
        let d = decision_from_result(&scan_result(None, Some("upstream 503".to_string())));
        assert_eq!(d.decision, "WARN");
        assert!(d.reason.contains("upstream 503"));
        assert_eq!(super::super::scan_exit_code(std::slice::from_ref(&d)), 2);
    }

    #[test]
    fn decision_no_verdict_no_error_is_fail_loud() {
        let d = decision_from_result(&scan_result(None, None));
        assert_eq!(d.decision, "WARN");
        assert!(d.reason.contains("no verdict returned"));
        assert_eq!(super::super::scan_exit_code(std::slice::from_ref(&d)), 2);
    }
}