provenant-cli 1.0.2

Fast Rust scanner for licenses, copyrights, package metadata, SBOMs, and provenance data.
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
// SPDX-FileCopyrightText: nexB Inc. and others
// ScanCode is a trademark of nexB Inc.
// SPDX-FileCopyrightText: Provenant contributors
// SPDX-License-Identifier: Apache-2.0
// Derived from ScanCode Toolkit (Apache-2.0); modified. See NOTICE.

use std::collections::{HashMap, HashSet};

use crate::models::{DatasourceId, FileInfo, LicenseDetection, Package};
use crate::utils::path::parent_dir;
use crate::utils::spdx::combine_license_expressions;

use super::PackageIx;
use super::classification::{is_legal_file, is_license_family_file};
use super::license_expression_render::{detection_token_maps, render_license_expression};
use super::output_indexes::OutputIndexes;
use super::summary_helpers::unique;

/// Packages synthesized purely from a dependency lockfile's resolved entries
/// (currently Swift `Package.resolved`) describe remote third-party packages, not a
/// package anchored by a local manifest. A co-located `LICENSE`/`README` therefore
/// belongs to the enclosing repository, not to these dependency records, so key-file
/// copyright/holder must not be promoted onto them (matching ScanCode, which leaves
/// them unset). The primary package retains a manifest datasource alongside the
/// resolved one, so it is not affected by this guard.
fn is_resolved_dependency_record(package: &Package) -> bool {
    !package.datasource_ids.is_empty()
        && package
            .datasource_ids
            .iter()
            .all(|id| matches!(id, DatasourceId::SwiftPackageResolved))
}

pub(super) fn promote_package_metadata_from_key_files(
    files: &[FileInfo],
    packages: &mut [Package],
    indexes: &OutputIndexes,
) {
    for (idx, package) in packages.iter_mut().enumerate() {
        if is_resolved_dependency_record(package) {
            continue;
        }

        let Some(key_file_indices) = indexes.key_file_indices_for_package(PackageIx(idx)) else {
            continue;
        };

        if package.copyright.is_none() {
            package.copyright = key_file_indices
                .iter()
                .filter_map(|index| files.get(index.0))
                .flat_map(|file| file.copyrights.iter())
                .map(|copyright| copyright.normalized_text().to_string())
                .next();
        }

        if package.holder.is_none() {
            let promoted_holders = unique(
                &key_file_indices
                    .iter()
                    .filter_map(|index| files.get(index.0))
                    .flat_map(|file| file.holders.iter())
                    .map(|holder| holder.holder.clone())
                    .collect::<Vec<_>>(),
            );
            if promoted_holders.len() == 1 {
                package.holder = promoted_holders.into_iter().next();
            }
        }
    }
}

/// Promotes a co-hosted legal file's detected license onto a package that declares
/// no license of its own.
///
/// This is the bounded post-assembly pass adopted in
/// [ADR 0010](../../docs/adr/0010-package-license-from-cohosted-files.md). Many
/// package formats carry no declared-license field (Go `go.mod`, autotools, Swift,
/// Bazel/Gradle sub-modules), so the only declared-license signal for such a
/// package is a `LICENSE`/`COPYING`/`NOTICE` file in its directory. ScanCode
/// attaches that license via `add_license_from_file`; this pass does the same under
/// strict guards:
///
/// - **Genuine absence only**: the package has no `declared_license_expression`,
///   `declared_license_expression_spdx`, or `extracted_license_statement` (the
///   manifest neither declared nor referenced a license).
/// - **Legal files only**: sourced from `is_legal_file` files in the package's own
///   directory — never `README`/source files.
/// - **Same-directory, sole-package only**: a legal file is adopted only when it
///   sits in a directory the package is anchored in (one of its `datafile_paths`)
///   *and* that directory anchors no other package. This bounds attribution to the
///   package's own directory and never smears a license across sibling packages or
///   down into nested sub-packages. (`for_packages` is not used here: it is only
///   populated by ecosystem-specific resource-assign passes, so it is empty for
///   exactly the formats this pass targets — Go, autotools, Swift, Bazel.)
/// - **`LICENSE` over `NOTICE` precedence**: when the co-located legal files
///   disagree, the canonically-named license file(s) (`LICENSE`/`LICENCE`/`COPYING`
///   family) take precedence over `NOTICE`/`COPYRIGHT`/`AUTHORS` files, and promotion
///   runs against that license-family subset. A `NOTICE` commonly lists the licenses
///   of *bundled third-party* code (e.g. prometheus's `NOTICE` →
///   `mit AND apache-2.0 AND bsd-new`), which is not the package's own declared
///   license (its `LICENSE` → `apache-2.0`). The full legal set is used only when no
///   canonical license file is present, preserving the prior `NOTICE`/`COPYING`-only
///   behavior. See ADR 0010 "LICENSE-over-NOTICE precedence".
/// - **Single legal file, or agreeing files**: within the chosen subset, promoted
///   from a *single* legal file — which may legitimately carry a compound license
///   (e.g. a repo-root `LICENSE` detecting `mpl-2.0 AND bsl-1.1`) — or when *multiple*
///   legal files resolve to one shared expression. The promoted expression is built
///   from the file's own `license_detections` (whose `license_expression`/`_spdx` are
///   reliably key and SPDX form), not from the file's `detected_license_expression`
///   string, which can already be SPDX-rendered when this pass runs. *Multiple* legal
///   files that resolve to *differing* expressions (e.g. dual `LICENSE-APACHE` +
///   `LICENSE-MIT`) are left unset rather than guessing an `AND`/`OR` combination. See
///   ADR 0010 "Single legal file with a compound license vs. multiple disagreeing
///   files".
/// - **Provenance preserved**: the legal file's `license_detections` are copied
///   onto the package, keeping each detection's `from_file` so consumers can tell a
///   co-hosted-file-derived license from a manifest-declared one.
pub(super) fn promote_package_declared_license_from_legal_files(
    files: &[FileInfo],
    packages: &mut [Package],
) {
    // Legal files (with their detections), grouped by their containing directory.
    let mut legal_files_by_dir: HashMap<String, Vec<&FileInfo>> = HashMap::new();
    for file in files.iter().filter(|file| is_legal_file(file)) {
        if file.license_detections.is_empty() {
            continue;
        }
        legal_files_by_dir
            .entry(parent_dir(&file.path).to_string())
            .or_default()
            .push(file);
    }
    if legal_files_by_dir.is_empty() {
        return;
    }

    // How many distinct packages are anchored (have a datafile) in each directory.
    let mut packages_per_dir: HashMap<String, usize> = HashMap::new();
    for package in packages.iter() {
        for dir in package_anchor_dirs(package) {
            *packages_per_dir.entry(dir).or_insert(0) += 1;
        }
    }

    for package in packages.iter_mut() {
        // Only fill a genuine absence; never override a manifest-declared or
        // manifest-referenced license.
        if package.declared_license_expression.is_some()
            || package.declared_license_expression_spdx.is_some()
            || package.extracted_license_statement.is_some()
        {
            continue;
        }
        // Remote dependency records (e.g. `Package.resolved`) are not anchored by a
        // local manifest, so a co-located legal file belongs to the enclosing repo.
        if is_resolved_dependency_record(package) {
            continue;
        }

        let colocated_legal_files: Vec<&FileInfo> = package_anchor_dirs(package)
            .into_iter()
            .filter(|dir| packages_per_dir.get(dir).copied() == Some(1))
            .filter_map(|dir| legal_files_by_dir.get(&dir))
            .flatten()
            .copied()
            .collect();
        if colocated_legal_files.is_empty() {
            continue;
        }

        // The legal files' agreed expression carries the authoritative operator
        // structure — crucially an `OR` choice, which must not be tightened to `AND`.
        //
        // When the co-located legal files *disagree*, prefer the canonically-named
        // license file(s) (`LICENSE`/`LICENCE`/`COPYING` family) over `NOTICE`/
        // `COPYRIGHT`/`AUTHORS` and resolve against that subset. A `NOTICE` typically
        // enumerates the licenses of *bundled third-party* code (e.g. prometheus's
        // `NOTICE` → `mit AND apache-2.0 AND bsd-new`), which must not drive (or block)
        // the package's own declared license (its `LICENSE` → `apache-2.0`). The
        // narrowing applies only on disagreement, and only when a canonical license
        // file is actually present, so an agreeing set (including its `NOTICE`
        // detections) and a `NOTICE`/`COPYRIGHT`/`AUTHORS`-only directory keep their
        // prior behavior. A subset that *still* disagrees (e.g. dual `LICENSE-APACHE` +
        // `LICENSE-MIT`) abstains. See ADR 0010 "LICENSE-over-NOTICE precedence".
        let Some((source_legal_files, file_expression)) =
            select_legal_files_and_expression(colocated_legal_files)
        else {
            continue;
        };

        let detections: Vec<LicenseDetection> = source_legal_files
            .iter()
            .flat_map(|file| file.license_detections.iter())
            .cloned()
            .collect();

        // Re-render the agreed expression into key and SPDX forms from the per-detection
        // key<->SPDX correspondence, preserving its `AND`/`OR`/`WITH` structure, then
        // canonically order operands to match ScanCode. `detected_license_expression`
        // now reliably holds key form, but the token maps index both spellings, so this
        // remains robust regardless of the source expression's form. The SPDX field is
        // rendered strictly — left unset (never key-form text) if any operand lacks an
        // SPDX id, e.g. a custom/unmapped license.
        let (token_to_key, token_to_spdx) = detection_token_maps(&detections);
        let Some(declared_key_expression) =
            render_license_expression(&file_expression, &token_to_key, false)
                .and_then(|key_form| combine_license_expressions([key_form]))
        else {
            continue;
        };
        package.declared_license_expression_spdx =
            render_license_expression(&file_expression, &token_to_spdx, true)
                .and_then(|spdx_form| combine_license_expressions([spdx_form]));
        package.declared_license_expression = Some(declared_key_expression);
        package.license_detections = detections;
    }
}

/// The unambiguous declared expression to promote from a package's co-located legal
/// files, or `None` when the result would be ambiguous.
///
/// - A *single* legal file contributes its own `detected_license_expression` verbatim
///   (the authoritative combined form, preserving its `AND`/`OR` structure rather than
///   re-combining its detections).
/// - *Multiple* legal files contribute only when they all resolve to the same
///   expression; otherwise the directory is genuinely dual-licensed and is left unset.
fn single_declared_expression(legal_files: &[&FileInfo]) -> Option<String> {
    let distinct_expressions = unique(
        &legal_files
            .iter()
            .filter_map(|file| file.detected_license_expression.clone())
            .collect::<Vec<_>>(),
    );
    let [expression] = distinct_expressions.as_slice() else {
        return None;
    };
    Some(expression.clone())
}

/// Chooses the legal files to promote from and their agreed expression, applying the
/// `LICENSE`-over-`NOTICE` precedence (ADR 0010).
///
/// - If the full co-located set already agrees on one expression, it is used as-is
///   (its `NOTICE`/`COPYRIGHT`/`AUTHORS` detections included).
/// - If the set disagrees, the canonical `LICENSE`/`LICENCE`/`COPYING` family takes
///   precedence and the agreement test is re-run on that subset; a subset that still
///   disagrees (dual `LICENSE-*`) abstains.
/// - A *sole* or *agreeing* `NOTICE`/`COPYRIGHT`/`AUTHORS` set still promotes via the
///   first branch. Only a *disagreeing* set with no canonical license file abstains
///   (returns `None`) — matching prior behavior, where a `NOTICE`-vs-`COPYRIGHT`
///   disagreement was never promoted either.
///
/// Returns `None` (abstain) when the chosen set has no single agreed expression.
fn select_legal_files_and_expression(
    colocated_legal_files: Vec<&FileInfo>,
) -> Option<(Vec<&FileInfo>, String)> {
    if let Some(expression) = single_declared_expression(&colocated_legal_files) {
        return Some((colocated_legal_files, expression));
    }
    let license_family_files: Vec<&FileInfo> = colocated_legal_files
        .iter()
        .copied()
        .filter(|file| is_license_family_file(file))
        .collect();
    if license_family_files.is_empty() {
        return None;
    }
    let expression = single_declared_expression(&license_family_files)?;
    Some((license_family_files, expression))
}

/// The distinct directories a package is anchored in (the parent directory of each
/// of its datafiles).
fn package_anchor_dirs(package: &Package) -> HashSet<String> {
    package
        .datafile_paths
        .iter()
        .map(|datafile| parent_dir(datafile).to_string())
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::license_detection::MatcherKind;
    use crate::models::{LineNumber, Match, MatchScore, PackageData};

    fn package_with_datasources(datasources: &[DatasourceId]) -> Package {
        let mut package =
            Package::from_package_data(&PackageData::default(), "Package.resolved".to_string());
        package.datasource_ids = datasources.to_vec();
        package
    }

    /// A match whose `from_file` records the legal file it came from, matching the
    /// provenance real detections carry (see `FileInfo` license-detection plumbing).
    fn match_from(from_file: &str, expression: &str, spdx: &str) -> Match {
        Match {
            license_expression: expression.to_string(),
            license_expression_spdx: spdx.to_string(),
            from_file: Some(from_file.to_string()),
            start_line: LineNumber::ONE,
            end_line: LineNumber::ONE,
            matcher: MatcherKind::default(),
            score: MatchScore::MAX,
            matched_length: Some(1),
            match_coverage: Some(100.0),
            rule_relevance: Some(100),
            rule_identifier: String::new(),
            rule_url: None,
            matched_text: None,
            matched_text_diagnostics: None,
            referenced_filenames: None,
        }
    }

    fn detection(path: &str, expression: &str, spdx: &str) -> LicenseDetection {
        LicenseDetection {
            license_expression: expression.to_string(),
            license_expression_spdx: spdx.to_string(),
            matches: vec![match_from(path, expression, spdx)],
            detection_log: Vec::new(),
            identifier: String::new(),
        }
    }

    fn legal(path: &str, expression: &str, spdx: &str) -> FileInfo {
        let mut file = crate::post_processing::test_utils::file(path);
        file.license_detections = vec![detection(path, expression, spdx)];
        file.detected_license_expression = Some(expression.to_string());
        file
    }

    /// A single legal file carrying a *compound* license: several detections that all
    /// originate from the same file. `combined` is the file's own
    /// `detected_license_expression` (the authoritative combined form, e.g.
    /// `bsl-1.1 AND mpl-2.0` or `mit OR apache-2.0`), which need not be the
    /// `AND`-combination of the individual detections.
    fn legal_compound(path: &str, combined: &str, expressions: &[(&str, &str)]) -> FileInfo {
        let mut file = crate::post_processing::test_utils::file(path);
        file.license_detections = expressions
            .iter()
            .map(|(expression, spdx)| detection(path, expression, spdx))
            .collect();
        file.detected_license_expression = Some(combined.to_string());
        file
    }

    fn pkg(uid: &str, datafile: &str) -> Package {
        crate::post_processing::test_utils::package(uid, datafile)
    }

    #[test]
    fn promotes_single_colocated_legal_file() {
        let files = vec![legal("proj/LICENSE", "apache-2.0", "Apache-2.0")];
        let mut packages = vec![pkg("a", "proj/go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression.as_deref(),
            Some("apache-2.0")
        );
        assert_eq!(
            packages[0].declared_license_expression_spdx.as_deref(),
            Some("Apache-2.0")
        );
        assert_eq!(packages[0].license_detections.len(), 1);
    }

    #[test]
    fn does_not_override_manifest_declared_or_referenced_license() {
        let files = vec![legal("proj/LICENSE", "apache-2.0", "Apache-2.0")];
        let mut declared = pkg("a", "proj/go.mod");
        declared.declared_license_expression = Some("mit".to_string());
        declared.declared_license_expression_spdx = Some("MIT".to_string());
        let mut extracted_only = pkg("b", "other/go.mod");
        extracted_only.extracted_license_statement = Some("see LICENSE".to_string());
        let files2 = vec![legal("other/LICENSE", "apache-2.0", "Apache-2.0")];

        promote_package_declared_license_from_legal_files(
            &files,
            std::slice::from_mut(&mut declared),
        );
        promote_package_declared_license_from_legal_files(
            &files2,
            std::slice::from_mut(&mut extracted_only),
        );

        assert_eq!(declared.declared_license_expression.as_deref(), Some("mit"));
        assert_eq!(
            extracted_only.declared_license_expression, None,
            "an extracted-but-unresolved statement still blocks co-hosted promotion"
        );
    }

    #[test]
    fn skips_directory_hosting_multiple_packages() {
        let files = vec![legal("proj/LICENSE", "apache-2.0", "Apache-2.0")];
        let mut packages = vec![pkg("a", "proj/go.mod"), pkg("b", "proj/pom.xml")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(packages[0].declared_license_expression, None);
        assert_eq!(packages[1].declared_license_expression, None);
    }

    #[test]
    fn does_not_smear_root_license_into_nested_subpackage() {
        let files = vec![legal("proj/LICENSE", "apache-2.0", "Apache-2.0")];
        let mut packages = vec![pkg("root", "proj/go.mod"), pkg("sub", "proj/sub/go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression.as_deref(),
            Some("apache-2.0")
        );
        assert_eq!(
            packages[1].declared_license_expression, None,
            "nested sub-package must not inherit the root LICENSE"
        );
    }

    #[test]
    fn each_package_gets_its_own_colocated_license() {
        let files = vec![
            legal("proj/LICENSE", "apache-2.0", "Apache-2.0"),
            legal("proj/sub/LICENSE", "mit", "MIT"),
        ];
        let mut packages = vec![pkg("root", "proj/go.mod"), pkg("sub", "proj/sub/go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression.as_deref(),
            Some("apache-2.0")
        );
        assert_eq!(
            packages[1].declared_license_expression.as_deref(),
            Some("mit")
        );
    }

    #[test]
    fn abstains_when_colocated_legal_files_disagree() {
        let files = vec![
            legal("proj/LICENSE-APACHE", "apache-2.0", "Apache-2.0"),
            legal("proj/LICENSE-MIT", "mit", "MIT"),
        ];
        let mut packages = vec![pkg("a", "proj/go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression, None,
            "conflicting co-hosted licenses are left unset rather than guessed"
        );
    }

    #[test]
    fn promotes_single_file_compound_license() {
        // One legal file (terraform's repo-root `LICENSE`) legitimately detects a
        // compound license. Its own combined expression must be promoted rather than
        // abstained on as if it were separate disagreeing files.
        let files = vec![legal_compound(
            "proj/LICENSE",
            // The file's own detected expression in detection order; promotion should
            // canonically reorder it to match ScanCode.
            "mpl-2.0 AND bsl-1.1",
            &[("mpl-2.0", "MPL-2.0"), ("bsl-1.1", "BUSL-1.1")],
        )];
        let mut packages = vec![pkg("a", "proj/go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression.as_deref(),
            Some("bsl-1.1 AND mpl-2.0"),
            "a single legal file's compound license is promoted as its own canonically ordered expression"
        );
        assert_eq!(
            packages[0].declared_license_expression_spdx.as_deref(),
            Some("BUSL-1.1 AND MPL-2.0")
        );
        assert_eq!(packages[0].license_detections.len(), 2);
    }

    #[test]
    fn promotes_key_form_even_when_file_expression_is_spdx() {
        // Regression guard: a legal file's own `detected_license_expression` can be in
        // SPDX form when this pass runs, while its detections still carry ScanCode keys.
        // The promoted key field must be derived from the detections (ScanCode keys),
        // with a matching SPDX field — never the file's SPDX string in the key field
        // with a null SPDX field.
        let files = vec![legal_compound(
            "proj/LICENSE",
            "BUSL-1.1 AND MPL-2.0", // file expression already rendered in SPDX form
            &[("mpl-2.0", "MPL-2.0"), ("bsl-1.1", "BUSL-1.1")],
        )];
        let mut packages = vec![pkg("a", "proj/go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression.as_deref(),
            Some("bsl-1.1 AND mpl-2.0"),
            "key field must be ScanCode keys from the detections, not the file's SPDX string"
        );
        assert_eq!(
            packages[0].declared_license_expression_spdx.as_deref(),
            Some("BUSL-1.1 AND MPL-2.0"),
            "SPDX field must be populated and match the key expression's operands"
        );
    }

    #[test]
    fn preserves_file_level_or_even_with_separate_detections() {
        // The legal file's own expression is an `OR` choice while its licenses are
        // present as separate detections. The agreed file-level `OR` must be preserved,
        // NOT tightened to a stricter `AND` by re-combining the detections.
        let files = vec![legal_compound(
            "proj/LICENSE",
            "apache-2.0 OR mit",
            &[("apache-2.0", "Apache-2.0"), ("mit", "MIT")],
        )];
        let mut packages = vec![pkg("a", "proj/go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression.as_deref(),
            Some("apache-2.0 OR mit"),
            "a file-level OR must not be turned into AND even when its licenses are separate detections"
        );
        assert_eq!(
            packages[0].declared_license_expression_spdx.as_deref(),
            Some("Apache-2.0 OR MIT")
        );
    }

    #[test]
    fn leaves_spdx_unset_when_a_license_has_no_spdx_id() {
        // A co-hosted legal file with a custom/unmapped license (no SPDX id) must still
        // get a key-form declared expression, but its SPDX field must be left absent —
        // never filled with key-form text.
        let files = vec![legal("proj/LICENSE", "custom-vendor-license", "")];
        let mut packages = vec![pkg("a", "proj/go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression.as_deref(),
            Some("custom-vendor-license"),
            "the key field is still promoted for an unmapped license"
        );
        assert_eq!(
            packages[0].declared_license_expression_spdx, None,
            "the SPDX field is absent rather than carrying key-form text for an unmapped license"
        );
    }

    #[test]
    fn promotes_single_file_alternative_license_without_forcing_and() {
        // A legal file whose detection is an `OR` choice must be promoted verbatim,
        // NOT silently tightened into a stricter `AND`. An `OR` license arises from a
        // single rule, so it is one detection carrying the `OR` expression.
        let files = vec![legal(
            "proj/LICENSE",
            "apache-2.0 OR mit",
            "Apache-2.0 OR MIT",
        )];
        let mut packages = vec![pkg("a", "proj/go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression.as_deref(),
            Some("apache-2.0 OR mit"),
            "an OR-shaped single-file expression must not be turned into an AND"
        );
        assert_eq!(
            packages[0].declared_license_expression_spdx.as_deref(),
            Some("Apache-2.0 OR MIT"),
            "the SPDX field must carry the same OR operator as the key expression"
        );
    }

    #[test]
    fn promotes_single_file_with_exception_keeps_spdx() {
        // A single detection whose expression is a `WITH` exception must still produce
        // a matching SPDX field: the per-operand key->SPDX mapping resolves `gpl-2.0`
        // and `classpath-exception-2.0` individually even though the detection records
        // them as one compound expression.
        let files = vec![legal(
            "proj/LICENSE",
            "gpl-2.0 WITH classpath-exception-2.0",
            "GPL-2.0 WITH Classpath-exception-2.0",
        )];
        let mut packages = vec![pkg("a", "proj/go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression.as_deref(),
            Some("gpl-2.0 WITH classpath-exception-2.0")
        );
        assert_eq!(
            packages[0].declared_license_expression_spdx.as_deref(),
            Some("GPL-2.0 WITH Classpath-exception-2.0"),
            "a compound WITH expression must not drop its SPDX field"
        );
    }

    #[test]
    fn abstains_when_multiple_files_disagree_even_with_provenance() {
        // Two *separate* legal files disagreeing remains ambiguous: unlike a single
        // compound file, their union must not be guessed into an `AND` expression.
        let files = vec![
            legal("proj/LICENSE-APACHE", "apache-2.0", "Apache-2.0"),
            legal("proj/LICENSE-MIT", "mit", "MIT"),
        ];
        let mut packages = vec![pkg("a", "proj/go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression, None,
            "two disagreeing legal files stay ambiguous even though each match has a from_file"
        );
    }

    #[test]
    fn promotes_when_multiple_files_agree() {
        // Two separate legal files that resolve to the *same* expression are not
        // ambiguous, so promotion still proceeds.
        let files = vec![
            legal("proj/LICENSE", "apache-2.0", "Apache-2.0"),
            legal("proj/COPYING", "apache-2.0", "Apache-2.0"),
        ];
        let mut packages = vec![pkg("a", "proj/go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression.as_deref(),
            Some("apache-2.0")
        );
    }

    #[test]
    fn promotes_when_license_and_notice_agree() {
        // Agreeing-path branch: a `LICENSE` and a `NOTICE` that resolve to the *same*
        // expression are not ambiguous, so the full set is used as-is (no narrowing)
        // and both detections are promoted. Guards the `Some(_)` arm of the selection
        // for a mixed license-family + attribution set.
        let files = vec![
            legal("LICENSE", "apache-2.0", "Apache-2.0"),
            legal("NOTICE", "apache-2.0", "Apache-2.0"),
        ];
        let mut packages = vec![pkg("a", "go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression.as_deref(),
            Some("apache-2.0")
        );
        assert_eq!(
            packages[0].license_detections.len(),
            2,
            "an agreeing LICENSE+NOTICE set keeps both detections (no narrowing)"
        );
    }

    #[test]
    fn prefers_license_over_disagreeing_notice() {
        // prometheus shape: the canonical `LICENSE` carries the project's own license
        // (`apache-2.0`) while `NOTICE` enumerates bundled third-party licenses
        // (`mit AND apache-2.0 AND bsd-new`). The two disagree; the package's declared
        // license must come from `LICENSE`, never the bundled-attribution `NOTICE`.
        let files = vec![
            legal("LICENSE", "apache-2.0", "Apache-2.0"),
            legal(
                "NOTICE",
                "mit AND apache-2.0 AND bsd-new",
                "MIT AND Apache-2.0 AND BSD-3-Clause",
            ),
        ];
        let mut packages = vec![pkg("a", "go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression.as_deref(),
            Some("apache-2.0"),
            "the canonical LICENSE wins over a bundled-attribution NOTICE"
        );
        assert_eq!(
            packages[0].declared_license_expression_spdx.as_deref(),
            Some("Apache-2.0")
        );
        assert_eq!(
            packages[0].license_detections.len(),
            1,
            "only the LICENSE detection is promoted, not the NOTICE detections"
        );
    }

    #[test]
    fn license_family_precedence_does_not_override_dual_license_files() {
        // Precedence operates within the license-family subset: genuine dual-licensing
        // expressed as separate `LICENSE-APACHE` + `LICENSE-MIT` files (both in the
        // license family) still disagrees, so the dual-license guard still abstains.
        let files = vec![
            legal("LICENSE-APACHE", "apache-2.0", "Apache-2.0"),
            legal("LICENSE-MIT", "mit", "MIT"),
            legal("NOTICE", "apache-2.0", "Apache-2.0"),
        ];
        let mut packages = vec![pkg("a", "go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression, None,
            "two disagreeing LICENSE-* files stay ambiguous; NOTICE does not break the tie"
        );
    }

    #[test]
    fn promotes_from_notice_when_no_license_family_file_present() {
        // No canonical LICENSE-family file: the full legal set is used, so a sole
        // `NOTICE` (or `COPYRIGHT`/`AUTHORS`) still promotes as before. This preserves
        // the prior behavior for directories that carry only a NOTICE.
        let files = vec![legal("NOTICE", "apache-2.0", "Apache-2.0")];
        let mut packages = vec![pkg("a", "go.mod")];

        promote_package_declared_license_from_legal_files(&files, &mut packages);

        assert_eq!(
            packages[0].declared_license_expression.as_deref(),
            Some("apache-2.0"),
            "a NOTICE-only directory still promotes when no LICENSE family file exists"
        );
    }

    #[test]
    fn skips_resolved_dependency_records() {
        let files = vec![legal("proj/LICENSE", "apache-2.0", "Apache-2.0")];
        let mut package = pkg("a", "proj/Package.resolved");
        package.datasource_ids = vec![DatasourceId::SwiftPackageResolved];

        promote_package_declared_license_from_legal_files(
            &files,
            std::slice::from_mut(&mut package),
        );

        assert_eq!(package.declared_license_expression, None);
    }

    #[test]
    fn resolved_dependency_record_detected_only_when_resolved_only() {
        // A package built purely from `Package.resolved` is a dependency record.
        assert!(is_resolved_dependency_record(&package_with_datasources(&[
            DatasourceId::SwiftPackageResolved
        ])));
        // The primary package retains its manifest datasource, so it still receives
        // co-located key-file metadata.
        assert!(!is_resolved_dependency_record(&package_with_datasources(
            &[
                DatasourceId::SwiftPackageManifestJson,
                DatasourceId::SwiftPackageResolved,
            ]
        )));
        assert!(!is_resolved_dependency_record(&package_with_datasources(
            &[DatasourceId::SwiftPackageManifestJson]
        )));
        // No datasource at all must not be treated as a dependency record.
        assert!(!is_resolved_dependency_record(&package_with_datasources(
            &[]
        )));
    }
}