Skip to content

Deterministic Verification

The deterministic core ensuring LLMs never evaluate versions: verbatim quote grounding, canonical Package URL validation and upstream registry checking, two-axis credibility scoring, OSV compilation, and univers version-range evaluation.

verify

Deterministic verification engine for zerobom.

HttpRegistryChecker(client=None, cache=None, timeout=5.0)

HTTP-based package existence verifier for 8 upstream package registries.

Initialize the HTTP registry existence verifier.

Parameters:

Name Type Description Default
client Client | None

Optional pre-configured httpx.Client (e.g., MockTransport in tests). When omitted, creates a hardened client with redirects disabled.

None
cache RegistryCache | None

Optional :class:RegistryCache to avoid redundant network calls.

None
timeout float

Request timeout in seconds when creating a default client.

5.0
Source code in src/zerobom/verify/purl.py
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
def __init__(
    self,
    client: httpx.Client | None = None,
    cache: RegistryCache | None = None,
    timeout: float = 5.0,
) -> None:
    """Initialize the HTTP registry existence verifier.

    Args:
        client: Optional pre-configured ``httpx.Client`` (e.g., ``MockTransport`` in tests).
            When omitted, creates a hardened client with redirects disabled.
        cache: Optional :class:`RegistryCache` to avoid redundant network calls.
        timeout: Request timeout in seconds when creating a default client.
    """
    self._owns_client = client is None
    # Disable redirects by default to prevent open-redirect/SSRF pivot attacks.
    self._client = (
        client
        if client is not None
        else create_pinned_httpx_client(
            timeout=timeout,
            headers={"User-Agent": DEFAULT_USER_AGENT},
        )
    )
    self._cache = cache

client property

Return the underlying httpx.Client instance.

check(purl)

Check upstream registry existence for purl with optional TTL caching.

Parameters:

Name Type Description Default
purl str

Canonical Package URL string.

required

Returns:

Type Description
RegistryStatus

EXISTS if confirmed, NOT_FOUND on 404/absent, SKIPPED for unsupported

RegistryStatus

ecosystems or invalid coordinates, or ERROR on network/5xx failures.

Source code in src/zerobom/verify/purl.py
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
def check(self, purl: str) -> RegistryStatus:
    """Check upstream registry existence for ``purl`` with optional TTL caching.

    Args:
        purl: Canonical Package URL string.

    Returns:
        ``EXISTS`` if confirmed, ``NOT_FOUND`` on 404/absent, ``SKIPPED`` for unsupported
        ecosystems or invalid coordinates, or ``ERROR`` on network/5xx failures.
    """
    if (
        _has_control_chars(purl)
        or len(purl) > MAX_PACKAGE_INPUT_LENGTH
        or "?" in purl
        or "#" in purl
    ):
        return RegistryStatus.SKIPPED

    if self._cache is not None:
        cached = self._cache.get(purl)
        if cached is not None:
            return cached

    try:
        parsed = PackageURL.from_string(purl)
    except ValueError:
        return RegistryStatus.SKIPPED

    status = self._query_registry(parsed)
    if self._cache is not None and status in (
        RegistryStatus.EXISTS,
        RegistryStatus.NOT_FOUND,
    ):
        self._cache.set(purl, status)
    return status

close()

Close the internal HTTP client if owned by this instance.

Source code in src/zerobom/verify/purl.py
629
630
631
632
def close(self) -> None:
    """Close the internal HTTP client if owned by this instance."""
    if self._owns_client:
        self._client.close()

InMemoryRegistryCache(ttl_seconds=86400.0, *, clock=time.time)

In-memory TTL cache for registry existence checks.

Attributes:

Name Type Description
ttl_seconds

Maximum age in seconds before cached entries expire.

Initialize an in-memory TTL registry cache.

Parameters:

Name Type Description Default
ttl_seconds float

Non-negative TTL duration in seconds.

86400.0
clock Callable[[], float]

Monotonic/wall clock provider returning epoch seconds.

time

Raises:

Type Description
ValueError

If ttl_seconds is negative.

Source code in src/zerobom/verify/purl.py
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
def __init__(
    self,
    ttl_seconds: float = 86400.0,
    *,
    clock: Callable[[], float] = time.time,
) -> None:
    """Initialize an in-memory TTL registry cache.

    Args:
        ttl_seconds: Non-negative TTL duration in seconds.
        clock: Monotonic/wall clock provider returning epoch seconds.

    Raises:
        ValueError: If ``ttl_seconds`` is negative.
    """
    if ttl_seconds < 0:
        raise ValueError("ttl_seconds must be non-negative")
    self.ttl_seconds = ttl_seconds
    self._clock = clock
    self._entries: dict[str, tuple[RegistryStatus, float]] = {}

get(purl)

Return cached status if present and within TTL, evicting stale entries.

Source code in src/zerobom/verify/purl.py
454
455
456
457
458
459
460
461
462
463
def get(self, purl: str) -> RegistryStatus | None:
    """Return cached status if present and within TTL, evicting stale entries."""
    entry = self._entries.get(purl)
    if entry is None:
        return None
    status, checked_at = entry
    if (self._clock() - checked_at) > self.ttl_seconds:
        self._entries.pop(purl, None)
        return None
    return status

set(purl, status)

Cache definitive EXISTS or NOT_FOUND statuses; ignore transient errors.

Source code in src/zerobom/verify/purl.py
465
466
467
468
469
def set(self, purl: str, status: RegistryStatus) -> None:
    """Cache definitive ``EXISTS`` or ``NOT_FOUND`` statuses; ignore transient errors."""
    if status not in (RegistryStatus.EXISTS, RegistryStatus.NOT_FOUND):
        return
    self._entries[purl] = (status, self._clock())

ParsedConstraint(events, exact_version, is_bounded, is_valid, reason=None) dataclass

Deterministic parse outcome of a single :class:VersionConstraint.

Attributes:

Name Type Description
events tuple[OsvRangeEvent, ...]

Compiled OSV range events when representing an interval.

exact_version str | None

Single matched version string when representing an exact constraint.

is_bounded bool

True if the constraint specifies an upper bound or exact version.

is_valid bool

True when all bounds parsed validly and were non-inverted.

reason str | None

Failure explanation when is_valid is False.

RegistryCache

Bases: Protocol

Protocol for caching package registry existence lookups.

get(purl)

Retrieve a cached status if present and unexpired.

Parameters:

Name Type Description Default
purl str

Canonical Package URL string.

required

Returns:

Name Type Description
Cached RegistryStatus | None

class:RegistryStatus or None on cache miss/expiration.

Source code in src/zerobom/verify/purl.py
407
408
409
410
411
412
413
414
415
def get(self, purl: str) -> RegistryStatus | None:
    """Retrieve a cached status if present and unexpired.

    Args:
        purl: Canonical Package URL string.

    Returns:
        Cached :class:`RegistryStatus` or ``None`` on cache miss/expiration.
    """

set(purl, status)

Persist a cacheable registry status for a canonical PURL.

Parameters:

Name Type Description Default
purl str

Canonical Package URL string.

required
status RegistryStatus

Lookup outcome (implementations should only cache definitive states).

required
Source code in src/zerobom/verify/purl.py
417
418
419
420
421
422
423
def set(self, purl: str, status: RegistryStatus) -> None:
    """Persist a cacheable registry status for a canonical PURL.

    Args:
        purl: Canonical Package URL string.
        status: Lookup outcome (implementations should only cache definitive states).
    """

RegistryChecker

Bases: Protocol

Protocol for checking whether a canonical PURL exists in its upstream registry.

check(purl)

Check upstream registry existence for a canonical PURL.

Parameters:

Name Type Description Default
purl str

Canonical Package URL string.

required

Returns:

Name Type Description
A RegistryStatus

class:RegistryStatus indicating existence, absence, skip, or error.

Source code in src/zerobom/verify/purl.py
584
585
586
587
588
589
590
591
592
def check(self, purl: str) -> RegistryStatus:
    """Check upstream registry existence for a canonical PURL.

    Args:
        purl: Canonical Package URL string.

    Returns:
        A :class:`RegistryStatus` indicating existence, absence, skip, or error.
    """

SqliteRegistryCache(db_path, ttl_seconds=86400.0, *, clock=time.time)

SQLite-backed TTL cache for registry existence checks using parameterized SQL.

Initialize a persistent SQLite TTL registry cache.

Parameters:

Name Type Description Default
db_path Path

Filesystem path to the SQLite database file (parent dirs created).

required
ttl_seconds float

Non-negative TTL duration in seconds.

86400.0
clock Callable[[], float]

Clock callable returning epoch seconds.

time

Raises:

Type Description
ValueError

If ttl_seconds is negative.

Source code in src/zerobom/verify/purl.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
def __init__(
    self,
    db_path: Path,
    ttl_seconds: float = 86400.0,
    *,
    clock: Callable[[], float] = time.time,
) -> None:
    """Initialize a persistent SQLite TTL registry cache.

    Args:
        db_path: Filesystem path to the SQLite database file (parent dirs created).
        ttl_seconds: Non-negative TTL duration in seconds.
        clock: Clock callable returning epoch seconds.

    Raises:
        ValueError: If ``ttl_seconds`` is negative.
    """
    if ttl_seconds < 0:
        raise ValueError("ttl_seconds must be non-negative")
    self._db_path = db_path
    self._ttl_seconds = ttl_seconds
    self._clock = clock
    self._db_path.parent.mkdir(parents=True, exist_ok=True)
    self._init_schema()

get(purl)

Look up a cached status by PURL, evicting expired or corrupted rows safely.

Source code in src/zerobom/verify/purl.py
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
def get(self, purl: str) -> RegistryStatus | None:
    """Look up a cached status by PURL, evicting expired or corrupted rows safely."""
    conn = self._connect()
    try:
        # Parameterized query prevents SQL injection regardless of PURL contents.
        row = conn.execute(
            "SELECT status, checked_at FROM registry_cache WHERE purl = ?",
            (purl,),
        ).fetchone()
        if row is None:
            return None
        raw_status, checked_at = str(row[0]), float(row[1])
        if (self._clock() - checked_at) > self._ttl_seconds:
            with conn:
                conn.execute("DELETE FROM registry_cache WHERE purl = ?", (purl,))
            return None
        try:
            return RegistryStatus(raw_status)
        except ValueError:
            # Fail safely and evict unrecognized status strings if DB was tampered/corrupted.
            with conn:
                conn.execute("DELETE FROM registry_cache WHERE purl = ?", (purl,))
            return None
    finally:
        conn.close()

schema_version()

Return the current SQLite PRAGMA user_version integer.

Source code in src/zerobom/verify/purl.py
525
526
527
528
529
530
531
532
def schema_version(self) -> int:
    """Return the current SQLite ``PRAGMA user_version`` integer."""
    conn = self._connect()
    try:
        row = conn.execute("PRAGMA user_version").fetchone()
        return int(row[0]) if row is not None else 0
    finally:
        conn.close()

set(purl, status)

Upsert definitive EXISTS or NOT_FOUND results using parameterized SQL.

Source code in src/zerobom/verify/purl.py
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
def set(self, purl: str, status: RegistryStatus) -> None:
    """Upsert definitive ``EXISTS`` or ``NOT_FOUND`` results using parameterized SQL."""
    if status not in (RegistryStatus.EXISTS, RegistryStatus.NOT_FOUND):
        return
    conn = self._connect()
    try:
        with conn:
            conn.execute(
                """
                INSERT INTO registry_cache (purl, status, checked_at)
                VALUES (?, ?, ?)
                ON CONFLICT(purl) DO UPDATE SET
                    status = excluded.status,
                    checked_at = excluded.checked_at
                """,
                (purl, status.value, self._clock()),
            )
    finally:
        conn.close()

build_package_queries(advisory)

Build deduplicated :class:PackageQuery entries from an :class:OsvAdvisory.

Parameters:

Name Type Description Default
advisory OsvAdvisory

Compiled OSV advisory containing one or more affected packages.

required

Returns:

Type Description
tuple[PackageQuery, ...]

Tuple of :class:PackageQuery descriptors for query-driven inventory backends.

Source code in src/zerobom/verify/osv_compiler.py
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
def build_package_queries(advisory: OsvAdvisory) -> tuple[PackageQuery, ...]:
    """Build deduplicated :class:`PackageQuery` entries from an :class:`OsvAdvisory`.

    Args:
        advisory: Compiled OSV advisory containing one or more affected packages.

    Returns:
        Tuple of :class:`PackageQuery` descriptors for query-driven inventory backends.
    """
    queries: list[PackageQuery] = []
    seen: set[tuple[str, str]] = set()

    for affected in advisory.affected:
        canonical_purl, _ = _canonicalize_component_purl(affected.package.purl)
        parsed = PackageURL.from_string(canonical_purl)
        _, distro_release = parse_osv_ecosystem(affected.package.ecosystem)
        key = (canonical_purl, affected.package.ecosystem)
        if key in seen:
            continue
        seen.add(key)
        queries.append(
            PackageQuery(
                canonical_purl=canonical_purl,
                ecosystem=parsed.type,
                osv_ecosystem=affected.package.ecosystem,
                namespace=parsed.namespace,
                name=parsed.name,
                distro_release=distro_release,
            )
        )

    return tuple(queries)

canonicalize_url(url)

Canonicalize an article URL for deterministic advisory ID generation.

Lowercases scheme and host, strips URL fragments and trailing slashes, removes common marketing/tracking query parameters (e.g., utm_*, fbclid), and sorts remaining query parameters.

Parameters:

Name Type Description Default
url str

Source article URI string.

required

Returns:

Type Description
str

Normalized canonical URL string.

Source code in src/zerobom/verify/osv_compiler.py
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
def canonicalize_url(url: str) -> str:
    """Canonicalize an article URL for deterministic advisory ID generation.

    Lowercases scheme and host, strips URL fragments and trailing slashes, removes common
    marketing/tracking query parameters (e.g., ``utm_*``, ``fbclid``), and sorts remaining
    query parameters.

    Args:
        url: Source article URI string.

    Returns:
        Normalized canonical URL string.
    """
    parsed = urlparse(url.strip())
    scheme = parsed.scheme.lower()
    netloc = parsed.netloc.lower()
    path = parsed.path.rstrip("/")

    filtered_params = [
        (k, v)
        for k, v in parse_qsl(parsed.query, keep_blank_values=True)
        if not k.lower().startswith("utm_") and k.lower() not in _TRACKING_QUERY_PARAMS
    ]
    filtered_params.sort()
    query = urlencode(filtered_params, doseq=True)
    return urlunparse((scheme, netloc, path, parsed.params, query, ""))

check_distro_quote_grounding(claim, *, ecosystem, namespace)

Verify OS distro package claims are anchored in distro evidence in their quotes.

Prevents LLMs from fabricating deb/rpm/apk package claims out of upstream application advisories that never mention OS vendor packages.

Parameters:

Name Type Description Default
claim ExtractedPackageClaim

Extracted package claim under evaluation.

required
ecosystem str | None

Normalized PURL ecosystem type (e.g., "deb", "rpm", "apk").

required
namespace str | None

Normalized package namespace (e.g., "debian", "ubuntu").

required

Returns:

Type Description
tuple[bool, tuple[str, ...]]

Tuple (is_grounded_distro, diagnostic_reasons).

Source code in src/zerobom/verify/grounding.py
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
def check_distro_quote_grounding(
    claim: ExtractedPackageClaim,
    *,
    ecosystem: str | None,
    namespace: str | None,
) -> tuple[bool, tuple[str, ...]]:
    """Verify OS distro package claims are anchored in distro evidence in their quotes.

    Prevents LLMs from fabricating ``deb``/``rpm``/``apk`` package claims out of upstream
    application advisories that never mention OS vendor packages.

    Args:
        claim: Extracted package claim under evaluation.
        ecosystem: Normalized PURL ecosystem type (e.g., ``"deb"``, ``"rpm"``, ``"apk"``).
        namespace: Normalized package namespace (e.g., ``"debian"``, ``"ubuntu"``).

    Returns:
        Tuple ``(is_grounded_distro, diagnostic_reasons)``.
    """
    if ecosystem not in {"deb", "rpm", "apk"}:
        return True, ()

    combined = normalize_text(" ".join((claim.evidence_quote, *claim.supporting_quotes)))
    if not combined:
        return False, ("OS distro claim has empty evidence quote.",)

    if (
        _DISTRO_MENTION_RE.search(combined) is not None
        or _DISTRO_VERSION_MARKER_RE.search(combined) is not None
    ):
        return True, ()

    if namespace:
        ns_norm = normalize_text(namespace)
        if ns_norm and _contains_token_boundary(combined, ns_norm):
            return True, ()

    return False, (
        f"OS distro claim ({ecosystem}/{namespace or 'unknown'}) lacks distro package or version "
        "evidence inside the cited quote.",
    )

check_quote_polarity(claim)

Verify that quote semantics align with claimed fixed bounds and vulnerability context.

Catches common LLM inversions where tool copyright banners, compromised/malicious package versions, or inclusive through <ver> phrases are mislabeled as fixed.

Parameters:

Name Type Description Default
claim ExtractedPackageClaim

Extracted package claim to validate deterministically.

required

Returns:

Type Description
tuple[bool, tuple[str, ...]]

Tuple (is_consistent, diagnostic_reasons).

Source code in src/zerobom/verify/grounding.py
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
def check_quote_polarity(claim: ExtractedPackageClaim) -> tuple[bool, tuple[str, ...]]:
    """Verify that quote semantics align with claimed ``fixed`` bounds and vulnerability context.

    Catches common LLM inversions where tool copyright banners, compromised/malicious package
    versions, or inclusive ``through <ver>`` phrases are mislabeled as ``fixed``.

    Args:
        claim: Extracted package claim to validate deterministically.

    Returns:
        Tuple ``(is_consistent, diagnostic_reasons)``.
    """
    combined = normalize_text(" ".join((claim.evidence_quote, *claim.supporting_quotes)))
    if not combined:
        return True, ()

    reasons: list[str] = []

    # 1) Reject copyright/tool-banner quotes that lack any vulnerability/fix context.
    if not _VULN_CONTEXT_PHRASE_RE.search(combined) and (
        re.search(r"\bcopyright\b", combined) is not None
    ):
        reasons.append(
            "Evidence quote appears to be a copyright or banner notice without vulnerability "
            "context."
        )

    has_fix_phrasing = _FIX_PHRASING_RE.search(combined) is not None
    has_malicious_phrase = _MALICIOUS_COMPROMISE_PHRASE_RE.search(combined) is not None

    for constraint in claim.version_constraints:
        if constraint.fixed is None:
            continue
        fixed_clean = normalize_text(constraint.fixed)
        bare_fixed = (
            fixed_clean[1:] if fixed_clean.startswith("v") and len(fixed_clean) > 1 else fixed_clean
        )
        escaped_fixed = re.escape(bare_fixed)
        ver_pat = rf"(?<![a-z0-9.])v?{escaped_fixed}(?![a-z0-9])"

        # 2) Malicious/compromised package wording without fix language must not claim "fixed".
        if has_malicious_phrase and not has_fix_phrasing:
            reasons.append(
                f"Claim sets fixed='{constraint.fixed}' while quote describes a compromised or "
                "malicious release without naming a fix version."
            )
            continue

        # 3) Inclusive or confirmed-vulnerable wording paired with `fixed` -> polarity conflict.
        inclusive_re = re.compile(
            rf"(?:\b(?:through|up\s+to\s+and\s+including)\s+{ver_pat}|"
            rf"{ver_pat}\s+and\s+(?:earlier|prior|older|below)|"
            rf"\b(?:confirmed\s+against|got\s+code\s+execution)\b[^.?!]{{0,60}}{ver_pat})",
            re.IGNORECASE,
        )
        if inclusive_re.search(combined) is not None and not _quote_has_explicit_fix_for_version(
            combined, bare_fixed
        ):
            reasons.append(
                f"Claim sets fixed='{constraint.fixed}' while quote describes it as an inclusive "
                "or confirmed-affected version."
            )

    return (len(reasons) == 0), tuple(dict.fromkeys(reasons))

compile_osv_advisory(advisory, report, *, article=None, advisory_id=None, modified_at=None)

Compile accepted, verified claims into a standard OSV v1.6.7 advisory.

Parameters:

Name Type Description Default
advisory ExtractedAdvisory

Original extracted advisory candidate.

required
report CredibilityReport

Verification and credibility report containing accepted_claims.

required
article RawArticle | None

Optional source :class:RawArticle providing publisher metadata and dates.

None
advisory_id str | None

Optional explicit identifier overriding deterministic PRECVE hashing.

None
modified_at datetime | None

Optional modification timestamp overriding published.

None

Returns:

Type Description
OsvAdvisory | None

A validated :class:OsvAdvisory instance, or None if no accepted claims remain.

Source code in src/zerobom/verify/osv_compiler.py
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
def compile_osv_advisory(
    advisory: ExtractedAdvisory,
    report: CredibilityReport,
    *,
    article: RawArticle | None = None,
    advisory_id: str | None = None,
    modified_at: datetime | None = None,
) -> OsvAdvisory | None:
    """Compile accepted, verified claims into a standard OSV v1.6.7 advisory.

    Args:
        advisory: Original extracted advisory candidate.
        report: Verification and credibility report containing ``accepted_claims``.
        article: Optional source :class:`RawArticle` providing publisher metadata and dates.
        advisory_id: Optional explicit identifier overriding deterministic ``PRECVE`` hashing.
        modified_at: Optional modification timestamp overriding ``published``.

    Returns:
        A validated :class:`OsvAdvisory` instance, or ``None`` if no accepted claims remain.
    """
    if not report.accepted_claims:
        return None

    # Prevent lower-confidence, weakly grounded, or unbounded TRIAGE claims from piggybacking
    # inside an AUTO advisory.
    if report.routing == RoutingDecision.AUTO:
        eligible_claims = tuple(
            cr
            for cr in report.accepted_claims
            if cr.routing == RoutingDecision.AUTO
            and cr.grounding.status == GroundingStatus.VERIFIED
            and cr.has_bounded_version_range
        )
        eligible_ids = {id(cr) for cr in eligible_claims}
        held_triage_purls = tuple(
            dict.fromkeys(
                cr.purl.canonical_purl
                for cr in report.accepted_claims
                if id(cr) not in eligible_ids and cr.purl.canonical_purl is not None
            )
        )
    else:
        eligible_claims = report.accepted_claims
        held_triage_purls = ()

    if not eligible_claims:
        return None

    grouped: dict[tuple[str, str], list[Any]] = {}
    for claim_result in eligible_claims:
        canonical_purl = claim_result.purl.canonical_purl
        base_osv_eco = claim_result.purl.osv_ecosystem
        purl_type = claim_result.purl.ecosystem
        if canonical_purl is None or base_osv_eco is None or purl_type is None:
            continue
        formatted_eco = _format_claim_osv_ecosystem(
            base_osv_eco,
            purl_type,
            claim_result.claim.distro_release,
        )
        grouped.setdefault((canonical_purl, formatted_eco), []).append(claim_result)

    if not grouped:
        return None

    affected_entries: list[OsvAffected] = []
    for (canonical_purl, group_osv_ecosystem), group_claims in grouped.items():
        first_purl = group_claims[0].purl
        if first_purl.ecosystem is None or first_purl.name is None:
            # Fail closed rather than using assert, which is stripped under python -O.
            continue

        pkg = OsvPackage(
            ecosystem=group_osv_ecosystem,
            name=_osv_package_name(
                first_purl.ecosystem,
                first_purl.namespace,
                first_purl.name,
            ),
            purl=canonical_purl,
        )

        events: list[OsvRangeEvent] = []
        exact_versions: list[str] = []
        seen_exact: set[str] = set()
        group_quotes: list[str] = []
        seen_group_quotes: set[str] = set()

        for claim_result in group_claims:
            for quote in (
                claim_result.claim.evidence_quote,
                *claim_result.claim.supporting_quotes,
            ):
                if quote not in seen_group_quotes:
                    seen_group_quotes.add(quote)
                    group_quotes.append(quote)
            for constraint in claim_result.claim.version_constraints:
                parsed = parse_version_constraint(
                    first_purl.ecosystem,
                    constraint,
                    package_name=first_purl.name,
                )
                if not parsed.is_valid:
                    continue
                if parsed.exact_version is not None:
                    if parsed.exact_version not in seen_exact:
                        seen_exact.add(parsed.exact_version)
                        exact_versions.append(parsed.exact_version)
                elif parsed.events:
                    events.extend(parsed.events)

        ranges: tuple[OsvRange, ...] = ()
        if events:
            ranges = (
                OsvRange(
                    type=_osv_range_type(first_purl.ecosystem),
                    events=tuple(events),
                ),
            )

        # Skip hollow OsvAffected entries when zero valid ranges or exact versions compiled.
        if not ranges and not exact_versions:
            continue

        worst_grounding = (
            GroundingStatus.UNGROUNDED.value
            if any(cr.grounding.status == GroundingStatus.UNGROUNDED for cr in group_claims)
            else GroundingStatus.QUOTE_ONLY_WEAK.value
            if any(cr.grounding.status == GroundingStatus.QUOTE_ONLY_WEAK for cr in group_claims)
            else GroundingStatus.VERIFIED.value
        )
        agg_registry = (
            RegistryStatus.EXISTS.value
            if any(cr.purl.registry_status == RegistryStatus.EXISTS for cr in group_claims)
            else RegistryStatus.ERROR.value
            if any(cr.purl.registry_status == RegistryStatus.ERROR for cr in group_claims)
            else RegistryStatus.SKIPPED.value
        )
        group_routing = (
            RoutingDecision.AUTO.value
            if all(cr.routing == RoutingDecision.AUTO for cr in group_claims)
            else RoutingDecision.TRIAGE.value
        )
        group_aliases = list(
            dict.fromkeys(alias for cr in group_claims for alias in cr.claim.claim_aliases)
        )
        aff_zerobom_meta: dict[str, Any] = {
            "evidence_quotes": group_quotes,
            "grounding_status": worst_grounding,
            "registry_status": agg_registry,
            "routing": group_routing,
        }
        if group_aliases:
            aff_zerobom_meta["aliases"] = group_aliases

        affected_entries.append(
            OsvAffected(
                package=pkg,
                ranges=ranges,
                versions=tuple(exact_versions),
                database_specific={"zerobom": aff_zerobom_meta},
            )
        )

    if not affected_entries:
        return None

    published = (
        advisory.published_at
        or (article.published_at if article is not None else None)
        or datetime.now(UTC)
    )
    modified = modified_at or published

    resolved_id = advisory_id or generate_precve_id(
        advisory.article_url,
        tuple(entry.package.purl for entry in affected_entries),
        published_at=published,
    )

    refs: list[OsvReference] = []
    seen_refs: set[tuple[str, str]] = set()

    def _add_ref(ref_type: Any, url: str | None) -> None:
        if not url:
            return
        cleaned = url.strip()
        if not cleaned:
            return
        key = (str(ref_type), cleaned)
        if key not in seen_refs:
            seen_refs.add(key)
            refs.append(OsvReference(type=ref_type, url=cleaned))

    _add_ref("ARTICLE", advisory.article_url)
    for claim_result in eligible_claims:
        _add_ref("FIX", claim_result.claim.fix_commit_url)
        _add_ref("EVIDENCE", claim_result.claim.poc_url)
    for ref_url in advisory.references:
        _add_ref("WEB", ref_url)

    collected_quotes: list[str] = []
    seen_quotes: set[str] = set()
    for cr in eligible_claims:
        for quote in (cr.claim.evidence_quote, *cr.claim.supporting_quotes):
            if quote not in seen_quotes:
                seen_quotes.add(quote)
                collected_quotes.append(quote)

    merged_aliases = tuple(
        dict.fromkeys(
            (
                *advisory.known_aliases,
                *(alias for cr in eligible_claims for alias in cr.claim.claim_aliases),
            )
        )
    )

    zerobom_meta: dict[str, Any] = {
        "source_tier": report.source_tier.value,
        "source_tier_weight": report.source_tier_weight,
        "extraction_specificity": report.extraction_specificity,
        "composite_score": report.composite_score,
        "routing": report.routing.value,
        "severity": advisory.severity.value,
        "cwe_ids": list(advisory.cwe_ids),
        "evidence_quotes": collected_quotes,
    }
    if advisory.article_type is not None:
        zerobom_meta["article_type"] = advisory.article_type.value
    if held_triage_purls:
        zerobom_meta["held_for_triage_purls"] = list(held_triage_purls)
    if article is not None:
        zerobom_meta["source_name"] = article.source_name
    if advisory.prompt_version is not None:
        zerobom_meta["prompt_version"] = advisory.prompt_version
    if advisory.extractor_model is not None:
        zerobom_meta["extractor_model"] = advisory.extractor_model

    return OsvAdvisory(
        id=resolved_id,
        modified=modified,
        published=published,
        summary=advisory.summary,
        details=advisory.details,
        aliases=merged_aliases,
        affected=tuple(affected_entries),
        references=tuple(refs),
        database_specific={"zerobom": zerobom_meta},
    )

detect_overlapping_branch_ranges(ecosystem, constraints, *, package_name=None)

Detect conflicting multi-branch intervals (e.g., multiple introduced="0" branches).

When a multi-branch advisory omits branch lower bounds and emits < 4.1.1 | < 3.0.24, the resulting introduced: "0" intervals cause patched older LTS releases (3.0.24) to falsely match < 4.1.1.

Parameters:

Name Type Description Default
ecosystem str | None

Canonical PURL ecosystem type or OSV ecosystem name.

required
constraints Sequence[VersionConstraint]

Constraints belonging to one claim or merged (purl, ecosystem) group.

required
package_name str | None

Optional canonical package name used to strip redundant NVR prefixes.

None

Returns:

Type Description
tuple[bool, str | None]

Tuple (has_overlap, diagnostic_reason).

Source code in src/zerobom/verify/osv_compiler.py
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
def detect_overlapping_branch_ranges(
    ecosystem: str | None,
    constraints: Sequence[VersionConstraint],
    *,
    package_name: str | None = None,
) -> tuple[bool, str | None]:
    """Detect conflicting multi-branch intervals (e.g., multiple ``introduced="0"`` branches).

    When a multi-branch advisory omits branch lower bounds and emits ``< 4.1.1 | < 3.0.24``,
    the resulting ``introduced: "0"`` intervals cause patched older LTS releases (``3.0.24``)
    to falsely match ``< 4.1.1``.

    Args:
        ecosystem: Canonical PURL ecosystem type or OSV ecosystem name.
        constraints: Constraints belonging to one claim or merged ``(purl, ecosystem)`` group.
        package_name: Optional canonical package name used to strip redundant NVR prefixes.

    Returns:
        Tuple ``(has_overlap, diagnostic_reason)``.
    """
    if ecosystem is None or not constraints:
        return False, None

    try:
        _get_range_class(ecosystem)
    except ValueError:
        return False, None

    # Tuple layout: (lo_str, lo_ver_or_none, hi_str, hi_ver, hi_is_inclusive, has_fixed_bound)
    intervals: list[tuple[str, Any, str, Any, bool, bool]] = []
    for item in constraints:
        parsed = parse_version_constraint(ecosystem, item, package_name=package_name)
        if not parsed.is_valid or len(parsed.events) != 2:
            continue
        intro_ev, close_ev = parsed.events[0], parsed.events[1]
        if intro_ev.introduced is None:
            continue
        lo_str = intro_ev.introduced
        hi_str = close_ev.fixed if close_ev.fixed is not None else close_ev.last_affected
        if hi_str is None:
            continue
        try:
            lo_ver = None if lo_str == "0" else parse_ecosystem_version(ecosystem, lo_str)
            hi_ver = parse_ecosystem_version(ecosystem, hi_str)
        except ValueError:
            continue
        intervals.append(
            (
                lo_str,
                lo_ver,
                hi_str,
                hi_ver,
                close_ev.last_affected is not None,
                close_ev.fixed is not None,
            )
        )

    if len(intervals) < 2:
        return False, None

    open_origin_uppers = {hi_str for lo_str, _, hi_str, _, _, _ in intervals if lo_str == "0"}
    if len(open_origin_uppers) >= 2:
        return True, (
            "Multiple release branches share open-origin introduced='0' bounds, which "
            "falsely flags patched older branches as vulnerable."
        )

    for idx_i, (lo_i, lo_ver_i, _hi_i, hi_ver_i, hi_inc_i, _is_fix_i) in enumerate(intervals):
        for idx_j, (_lo_j, _lo_ver_j, hi_j, hi_ver_j, _hi_inc_j, is_fix_j) in enumerate(intervals):
            if idx_i == idx_j or not is_fix_j:
                continue
            covers_lower = lo_ver_i is None or lo_ver_i <= hi_ver_j
            covers_upper = (hi_ver_j <= hi_ver_i) if hi_inc_i else (hi_ver_j < hi_ver_i)
            if covers_lower and covers_upper:
                return True, (
                    f"Version interval from {lo_i!r} overlaps another branch's fixed version "
                    f"{hi_j!r}."
                )

    return False, None

evaluate_component_against_advisory(advisory, component_purl, installed_version=None, *, sbom_source=None, asset=None)

Evaluate an SBOM component PURL and version against a compiled :class:OsvAdvisory.

Supports distro release compatibility filtering via ?distro= qualifiers and source package matching via ?upstream= qualifiers.

Parameters:

Name Type Description Default
advisory OsvAdvisory

Compiled OSV advisory.

required
component_purl str

SBOM component Package URL (may embed @version and qualifiers).

required
installed_version str | None

Explicit installed version overriding component_purl version.

None
sbom_source str | None

Optional source SBOM filename or inventory identifier for reporting.

None
asset AssetRef | None

Optional cloud-agnostic :class:AssetRef associated with the component.

None

Returns:

Name Type Description
A MatchResult | None

class:MatchResult if the package matches an affected entry (with is_vulnerable

MatchResult | None

set deterministically), or None if the advisory does not apply to this package.

Raises:

Type Description
ValueError

If no version is supplied via installed_version or component_purl, or if the PURL/version is malformed.

Source code in src/zerobom/verify/osv_compiler.py
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
def evaluate_component_against_advisory(
    advisory: OsvAdvisory,
    component_purl: str,
    installed_version: str | None = None,
    *,
    sbom_source: str | None = None,
    asset: AssetRef | None = None,
) -> MatchResult | None:
    """Evaluate an SBOM component PURL and version against a compiled :class:`OsvAdvisory`.

    Supports distro release compatibility filtering via ``?distro=`` qualifiers and source
    package matching via ``?upstream=`` qualifiers.

    Args:
        advisory: Compiled OSV advisory.
        component_purl: SBOM component Package URL (may embed ``@version`` and qualifiers).
        installed_version: Explicit installed version overriding ``component_purl`` version.
        sbom_source: Optional source SBOM filename or inventory identifier for reporting.
        asset: Optional cloud-agnostic :class:`AssetRef` associated with the component.

    Returns:
        A :class:`MatchResult` if the package matches an affected entry (with ``is_vulnerable``
        set deterministically), or ``None`` if the advisory does not apply to this package.

    Raises:
        ValueError: If no version is supplied via ``installed_version`` or ``component_purl``,
            or if the PURL/version is malformed.
    """
    component_canonical, purl_version = _canonicalize_component_purl(component_purl)
    version_str = installed_version if installed_version is not None else purl_version
    if not version_str:
        raise ValueError("installed_version must be supplied or embedded in component_purl")

    comp_distro, upstream_name, upstream_version = extract_purl_os_qualifiers(component_purl)
    return _match_canonical_purl_against_advisory(
        advisory,
        component_canonical=component_canonical,
        component_identifier=component_purl,
        installed_version=version_str,
        comp_distro=comp_distro,
        upstream_name=upstream_name,
        upstream_version=upstream_version,
        sbom_source=sbom_source,
        asset=asset,
    )

evaluate_inventory_component(advisory, component)

Evaluate a normalized :class:InventoryComponent against a compiled :class:OsvAdvisory.

Prioritizes raw PURL matching (preserving qualifiers), then pre-resolved canonical PURL, and finally safe non-generic name fallback for PURL-less SBOM entries.

Parameters:

Name Type Description Default
advisory OsvAdvisory

Compiled OSV advisory.

required
component InventoryComponent

Normalized inventory component returned by an inventory backend.

required

Returns:

Name Type Description
A MatchResult | None

class:MatchResult if the component matches an affected package, else None.

Source code in src/zerobom/verify/osv_compiler.py
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
def evaluate_inventory_component(
    advisory: OsvAdvisory,
    component: InventoryComponent,
) -> MatchResult | None:
    """Evaluate a normalized :class:`InventoryComponent` against a compiled :class:`OsvAdvisory`.

    Prioritizes raw PURL matching (preserving qualifiers), then pre-resolved canonical PURL,
    and finally safe non-generic name fallback for PURL-less SBOM entries.

    Args:
        advisory: Compiled OSV advisory.
        component: Normalized inventory component returned by an inventory backend.

    Returns:
        A :class:`MatchResult` if the component matches an affected package, else ``None``.
    """
    source = component.asset.location or component.asset.asset_id

    if component.purl is not None:
        comp_distro, upstream_name, upstream_version = extract_purl_os_qualifiers(component.purl)
        component_canonical, _ = _canonicalize_component_purl(component.purl)
        return _match_canonical_purl_against_advisory(
            advisory,
            component_canonical=component_canonical,
            component_identifier=component.purl,
            installed_version=component.version,
            comp_distro=comp_distro or component.distro_qualifier,
            upstream_name=upstream_name or component.upstream_package,
            upstream_version=upstream_version or component.upstream_version,
            sbom_source=source,
            asset=component.asset,
        )

    if component.canonical_purl is not None:
        return _match_canonical_purl_against_advisory(
            advisory,
            component_canonical=component.canonical_purl,
            component_identifier=component.canonical_purl,
            installed_version=component.version,
            comp_distro=component.distro_qualifier,
            upstream_name=component.upstream_package,
            upstream_version=component.upstream_version,
            sbom_source=source,
            asset=component.asset,
        )

    # PURL-less SBOM fallback: refuse generic names and verify distro/version safety.
    # Evaluate all matching affected entries so multi-ecosystem or multi-branch advisories
    # do not shadow a vulnerable match behind an earlier non-vulnerable branch.
    fallback_result: MatchResult | None = None
    for affected in advisory.affected:
        _, adv_release = parse_osv_ecosystem(affected.package.ecosystem)
        if not is_distro_compatible(adv_release, component.distro_qualifier):
            continue
        if not _name_fallback_matches(component, affected):
            continue
        try:
            result = _build_match_result(
                advisory,
                affected,
                component_identifier=f"name:{component.name}@{component.version}",
                eval_version=component.version,
                matched_via="name_fallback",
                sbom_source=source,
                asset=component.asset,
            )
        except ValueError:
            # Skip cross-ecosystem version syntax mismatches during untyped fallback scans.
            continue
        if result.is_vulnerable:
            return result
        if fallback_result is None:
            fallback_result = result

    return fallback_result

extract_claim_version_tokens(claim)

Extract non-"0" version tokens from a claim's structured constraints.

Parameters:

Name Type Description Default
claim ExtractedPackageClaim

Extracted package claim containing zero or more version constraints.

required

Returns:

Type Description
tuple[str, ...]

Deduplicated tuple of concrete version strings (excluding the OSV "0" sentinel).

Source code in src/zerobom/verify/grounding.py
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
def extract_claim_version_tokens(claim: ExtractedPackageClaim) -> tuple[str, ...]:
    """Extract non-``"0"`` version tokens from a claim's structured constraints.

    Args:
        claim: Extracted package claim containing zero or more version constraints.

    Returns:
        Deduplicated tuple of concrete version strings (excluding the OSV ``"0"`` sentinel).
    """
    tokens: list[str] = []
    seen: set[str] = set()

    def _add(token: str, *, allow_zero_sentinel: bool = False) -> None:
        cleaned = token.strip().rstrip(".,;:)")
        # Exclude OSV origin sentinel "0" on introduced bounds only; fixed="0" must be grounded.
        if not cleaned or (allow_zero_sentinel and cleaned == "0"):
            return
        key = cleaned.casefold()
        if key not in seen:
            seen.add(key)
            tokens.append(cleaned)

    for constraint in claim.version_constraints:
        upper = constraint.fixed or constraint.last_affected
        skip_implied_intro = constraint.introduced is not None and _is_implied_branch_origin(
            constraint.introduced, upper
        )
        implied_intro_key = (
            constraint.introduced.strip().rstrip(".,;:)").casefold()
            if skip_implied_intro and constraint.introduced is not None
            else None
        )
        if constraint.introduced is not None and not skip_implied_intro:
            _add(constraint.introduced, allow_zero_sentinel=True)
        for bound in (
            constraint.fixed,
            constraint.last_affected,
            constraint.exact,
        ):
            if bound is not None:
                _add(bound)
        if constraint.raw_specifier is not None:
            for match in _VERSION_TOKEN_RE.findall(constraint.raw_specifier):
                match_key = match.strip().rstrip(".,;:)").casefold()
                if implied_intro_key is not None and (
                    match_key == implied_intro_key
                    or match_key.lstrip("v") == implied_intro_key.lstrip("v")
                ):
                    continue
                _add(match)

    return tuple(tokens)

extract_package_match_candidates(raw_package_name, canonical_package_name=None)

Build normalized package name candidates for Stage 2 quote token verification.

Parameters:

Name Type Description Default
raw_package_name str

Raw package identifier or natural-language name from the claim.

required
canonical_package_name str | None

Optional canonical PURL name segment from PURL resolution.

None

Returns:

Type Description
tuple[str, ...]

Deduplicated tuple of normalized package name variants (including delimiter aliases).

Source code in src/zerobom/verify/grounding.py
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
def extract_package_match_candidates(
    raw_package_name: str,
    canonical_package_name: str | None = None,
) -> tuple[str, ...]:
    """Build normalized package name candidates for Stage 2 quote token verification.

    Args:
        raw_package_name: Raw package identifier or natural-language name from the claim.
        canonical_package_name: Optional canonical PURL ``name`` segment from PURL resolution.

    Returns:
        Deduplicated tuple of normalized package name variants (including delimiter aliases).
    """
    seeds: list[str] = []
    if canonical_package_name:
        seeds.append(canonical_package_name)
    seeds.append(raw_package_name)

    stripped = _strip_package_wrappers(raw_package_name)
    if stripped and stripped != raw_package_name:
        seeds.append(stripped)

    expanded: list[str] = []
    for seed in seeds:
        norm = normalize_text(seed)
        if not norm:
            continue
        expanded.append(norm)

        if norm.startswith("pkg:"):
            # Extract leaf package name when raw_package_name was already formatted as a PURL.
            without_qualifiers = norm.split("?", 1)[0].split("#", 1)[0].split("@", 1)[0]
            parts = without_qualifiers[4:].split("/")
            if parts:
                expanded.append(parts[-1])
            continue

        # Maven group:artifact -> also allow artifact alone as prose often drops groupId.
        if ":" in norm:
            artifact = norm.split(":", 1)[1].strip()
            if artifact:
                expanded.append(artifact)

        # Scoped npm (@scope/pkg) or Go/Maven path (github.com/org/repo) -> allow leaf name.
        if "/" in norm:
            leaf = norm.rsplit("/", 1)[-1].strip()
            if leaf:
                expanded.append(leaf)

    candidates: list[str] = []
    seen: set[str] = set()
    for item in expanded:
        variants = {
            item,
            item.replace("::", "-"),
            item.replace("::", "_"),
            item.replace("::", " "),
            item.replace("-", "::"),
            item.replace("-", "_"),
            item.replace("_", "-"),
            item.replace("-", " "),
            item.replace("_", " "),
        }
        for variant in variants:
            cleaned = _WHITESPACE_RE.sub(" ", variant).strip()
            if cleaned and cleaned not in seen:
                seen.add(cleaned)
                candidates.append(cleaned)

    return tuple(candidates)

extract_purl_os_qualifiers(purl_str)

Extract (distro_qualifier, upstream_name, upstream_version) from a PURL string.

Parameters:

Name Type Description Default
purl_str str

Raw Package URL string (possibly carrying ?distro=...&upstream=...).

required

Returns:

Type Description
tuple[str | None, str | None, str | None]

Tuple of (distro_qualifier, upstream_package_name, upstream_version).

Source code in src/zerobom/verify/osv_compiler.py
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
def extract_purl_os_qualifiers(purl_str: str) -> tuple[str | None, str | None, str | None]:
    """Extract ``(distro_qualifier, upstream_name, upstream_version)`` from a PURL string.

    Args:
        purl_str: Raw Package URL string (possibly carrying ``?distro=...&upstream=...``).

    Returns:
        Tuple of ``(distro_qualifier, upstream_package_name, upstream_version)``.
    """
    parsed = PackageURL.from_string(purl_str.strip())
    qualifiers = parsed.qualifiers
    if not isinstance(qualifiers, dict):
        return None, None, None

    raw_distro = qualifiers.get("distro")
    distro = raw_distro.strip() if isinstance(raw_distro, str) and raw_distro.strip() else None

    raw_upstream = qualifiers.get("upstream")
    if not isinstance(raw_upstream, str) or not raw_upstream.strip():
        return distro, None, None

    upstream_text = raw_upstream.strip()
    if "@" in upstream_text:
        up_name, up_ver = upstream_text.split("@", 1)
        return distro, up_name.strip() or None, up_ver.strip() or None
    if " (" in upstream_text and upstream_text.endswith(")"):
        up_name, up_ver_part = upstream_text[:-1].split(" (", 1)
        return distro, up_name.strip() or None, up_ver_part.strip() or None

    return distro, upstream_text, None

generate_precve_id(article_url, purls, published_at=None)

Generate a reproducible PRECVE-YYYY-XXXXXXXX identifier from URL and PURLs.

Parameters:

Name Type Description Default
article_url str

Source article URI.

required
purls Sequence[str]

Canonical PURLs included in the advisory.

required
published_at datetime | None

Optional publication date used for the YYYY segment.

None

Returns:

Type Description
str

Deterministic advisory identifier formatted as PRECVE-YYYY-XXXXXXXX.

Source code in src/zerobom/verify/osv_compiler.py
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
def generate_precve_id(
    article_url: str,
    purls: Sequence[str],
    published_at: datetime | None = None,
) -> str:
    """Generate a reproducible ``PRECVE-YYYY-XXXXXXXX`` identifier from URL and PURLs.

    Args:
        article_url: Source article URI.
        purls: Canonical PURLs included in the advisory.
        published_at: Optional publication date used for the ``YYYY`` segment.

    Returns:
        Deterministic advisory identifier formatted as ``PRECVE-YYYY-XXXXXXXX``.
    """
    year = (published_at or datetime.now(UTC)).year
    canonical_purls = "|".join(sorted(set(purls)))
    payload = f"{canonicalize_url(article_url)}|{canonical_purls}".encode()
    digest = hashlib.sha256(payload).hexdigest()[:8].upper()
    return f"PRECVE-{year}-{digest}"

is_distro_compatible(advisory_release, component_distro)

Return True if advisory and component distro releases are compatible or unspecified.

Parameters:

Name Type Description Default
advisory_release str | None

Optional release extracted from the advisory ecosystem.

required
component_distro str | None

Optional ?distro= qualifier extracted from the SBOM component.

required

Returns:

Type Description
bool

True if either side is unspecified (None) or both normalize identically.

Source code in src/zerobom/verify/osv_compiler.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def is_distro_compatible(advisory_release: str | None, component_distro: str | None) -> bool:
    """Return True if advisory and component distro releases are compatible or unspecified.

    Args:
        advisory_release: Optional release extracted from the advisory ecosystem.
        component_distro: Optional ``?distro=`` qualifier extracted from the SBOM component.

    Returns:
        ``True`` if either side is unspecified (``None``) or both normalize identically.
    """
    if advisory_release is None or component_distro is None:
        return True
    norm_adv = normalize_distro_qualifier(advisory_release)
    norm_comp = normalize_distro_qualifier(component_distro)
    if norm_adv is None or norm_comp is None:
        return True
    return norm_adv == norm_comp

is_version_affected(ecosystem, installed_version, affected)

Check whether installed_version matches an :class:OsvAffected entry.

Evaluates both explicit affected.versions (using ecosystem-native equality) and affected.ranges (via univers interval matching).

Parameters:

Name Type Description Default
ecosystem str

Ecosystem alias, canonical PURL type, or OSV ecosystem name.

required
installed_version str

Installed package version string.

required
affected OsvAffected

Compiled :class:OsvAffected entry.

required

Returns:

Type Description
bool

True if the version is vulnerable under exact versions or range intervals.

Source code in src/zerobom/verify/osv_compiler.py
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
def is_version_affected(
    ecosystem: str,
    installed_version: str,
    affected: OsvAffected,
) -> bool:
    """Check whether ``installed_version`` matches an :class:`OsvAffected` entry.

    Evaluates both explicit ``affected.versions`` (using ecosystem-native equality) and
    ``affected.ranges`` (via ``univers`` interval matching).

    Args:
        ecosystem: Ecosystem alias, canonical PURL type, or OSV ecosystem name.
        installed_version: Installed package version string.
        affected: Compiled :class:`OsvAffected` entry.

    Returns:
        ``True`` if the version is vulnerable under exact versions or range intervals.
    """
    resolved_eco = _resolve_affected_ecosystem(ecosystem, affected)
    installed = parse_ecosystem_version(resolved_eco, installed_version)

    for exact_ver in affected.versions:
        if parse_ecosystem_version(resolved_eco, exact_ver) == installed:
            return True

    return any(
        is_version_in_osv_range(resolved_eco, installed_version, osv_range)
        for osv_range in affected.ranges
    )

is_version_in_osv_range(ecosystem, installed_version, osv_range)

Deterministically evaluate whether installed_version falls within an :class:OsvRange.

Follows the OSV specification timeline algorithm: - Sorts events ascending by ecosystem-native univers version precedence (with introduced: "0" ordered strictly first). - Skips GIT ranges cleanly with a diagnostic warning. - Enforces any concrete limit event as a range-wide upper cap (< limit).

Parameters:

Name Type Description Default
ecosystem str

Ecosystem alias, canonical PURL type, or OSV ecosystem name.

required
installed_version str

Installed version string from an SBOM or package manifest.

required
osv_range OsvRange

OSV range containing introduced / fixed / last_affected / limit.

required

Returns:

Type Description
bool

True if installed_version matches any active interval in osv_range.

Raises:

Type Description
ValueError

If ecosystem is unsupported or any version bound fails parsing.

Source code in src/zerobom/verify/osv_compiler.py
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
def is_version_in_osv_range(
    ecosystem: str,
    installed_version: str,
    osv_range: OsvRange,
) -> bool:
    """Deterministically evaluate whether ``installed_version`` falls within an :class:`OsvRange`.

    Follows the OSV specification timeline algorithm:
    - Sorts ``events`` ascending by ecosystem-native ``univers`` version precedence (with
      ``introduced: "0"`` ordered strictly first).
    - Skips ``GIT`` ranges cleanly with a diagnostic warning.
    - Enforces any concrete ``limit`` event as a range-wide upper cap (``< limit``).

    Args:
        ecosystem: Ecosystem alias, canonical PURL type, or OSV ecosystem name.
        installed_version: Installed version string from an SBOM or package manifest.
        osv_range: OSV range containing ``introduced`` / ``fixed`` / ``last_affected`` / ``limit``.

    Returns:
        ``True`` if ``installed_version`` matches any active interval in ``osv_range``.

    Raises:
        ValueError: If ``ecosystem`` is unsupported or any version bound fails parsing.
    """
    if osv_range.type == "GIT":
        _logger.warning("Skipping unsupported OSV GIT range during ecosystem version evaluation.")
        return False

    range_cls = _get_range_class(ecosystem)
    installed = parse_ecosystem_version(ecosystem, installed_version)
    intervals, limits = _compile_sorted_osv_intervals(ecosystem, osv_range.events)

    limit_constraints: list[UniversVersionConstraint] = [
        UniversVersionConstraint(
            comparator="<",
            version=parse_ecosystem_version(ecosystem, lim_str),
        )
        for lim_str in limits
    ]
    for lim_c in limit_constraints:
        if installed >= lim_c.version:
            return False

    for intro_str, closing_event in intervals:
        if intro_str == "0" and closing_event is None:
            return True

        constraints: list[UniversVersionConstraint] = []
        intro_ver = None if intro_str == "0" else parse_ecosystem_version(ecosystem, intro_str)
        if intro_ver is not None:
            constraints.append(
                UniversVersionConstraint(
                    comparator=">=",
                    version=intro_ver,
                )
            )
        if closing_event is not None:
            if closing_event.fixed is not None:
                fixed_ver = parse_ecosystem_version(ecosystem, closing_event.fixed)
                if intro_ver is not None and intro_ver >= fixed_ver:
                    continue
                constraints.append(
                    UniversVersionConstraint(
                        comparator="<",
                        version=fixed_ver,
                    )
                )
            elif closing_event.last_affected is not None:
                la_ver = parse_ecosystem_version(ecosystem, closing_event.last_affected)
                if intro_ver is not None and intro_ver > la_ver:
                    continue
                constraints.append(
                    UniversVersionConstraint(
                        comparator="<=",
                        version=la_ver,
                    )
                )

        if not constraints:
            continue
        version_range = range_cls(constraints=constraints)
        if bool(version_range.contains(installed)):
            return True

    return False

normalize_distro_qualifier(raw_distro)

Normalize an OS distro qualifier or release tag into {family}-{release}.

Handles values such as "debian-11", "debian-11.8", "ubuntu-22.04", "alpine-v3.19", "alpine-3.19.1", "Red Hat:enterprise_linux:9", and common Debian/Ubuntu codenames.

Parameters:

Name Type Description Default
raw_distro str | None

Unnormalized distro qualifier string.

required

Returns:

Type Description
str | None

Canonical distro release identifier (e.g., "debian-11", "alpine-3.19"), or

str | None

None if empty or invalid.

Source code in src/zerobom/verify/osv_compiler.py
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
def normalize_distro_qualifier(raw_distro: str | None) -> str | None:
    """Normalize an OS distro qualifier or release tag into ``{family}-{release}``.

    Handles values such as ``"debian-11"``, ``"debian-11.8"``, ``"ubuntu-22.04"``,
    ``"alpine-v3.19"``, ``"alpine-3.19.1"``, ``"Red Hat:enterprise_linux:9"``, and common
    Debian/Ubuntu codenames.

    Args:
        raw_distro: Unnormalized distro qualifier string.

    Returns:
        Canonical distro release identifier (e.g., ``"debian-11"``, ``"alpine-3.19"``), or
        ``None`` if empty or invalid.
    """
    if raw_distro is None or _has_control_chars(raw_distro):
        return None
    cleaned = raw_distro.strip().lower()
    if not cleaned:
        return None

    normalized_sep = re.sub(r"[\s_:]+", "-", cleaned)
    normalized_sep = normalized_sep.replace("red-hat", "redhat")

    if normalized_sep in _DISTRO_CODENAME_ALIASES:
        return _DISTRO_CODENAME_ALIASES[normalized_sep]

    if match := _DISTRO_FAMILY_RE.match(normalized_sep):
        raw_family, raw_version = match.group(1).lower(), match.group(2)
        family = (
            "rhel"
            if raw_family in {"redhat", "rhel", "redhat-enterprise-linux", "enterprise-linux"}
            else raw_family
        )
        parts = raw_version.split(".")
        if family in _TWO_PART_RELEASE_DISTROS and len(parts) >= 2:
            release = f"{parts[0]}.{parts[1]}"
        else:
            release = parts[0]
        return f"{family}-{release}"

    return normalized_sep

normalize_ecosystem(raw)

Normalize an ecosystem alias into (canonical_purl_type, osv_ecosystem).

Parameters:

Name Type Description Default
raw str | None

Ecosystem string or alias (e.g., "Python", "Node.js", "deb").

required

Returns:

Type Description
tuple[str | None, str | None]

Tuple of (purl_type, osv_ecosystem), or (None, None) if unrecognized.

Source code in src/zerobom/verify/purl.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def normalize_ecosystem(raw: str | None) -> tuple[str | None, str | None]:
    """Normalize an ecosystem alias into ``(canonical_purl_type, osv_ecosystem)``.

    Args:
        raw: Ecosystem string or alias (e.g., ``"Python"``, ``"Node.js"``, ``"deb"``).

    Returns:
        Tuple of ``(purl_type, osv_ecosystem)``, or ``(None, None)`` if unrecognized.
    """
    if raw is None or _has_control_chars(raw):
        return None, None
    key = re.sub(r"\s+", " ", raw.strip().lower())
    if not key:
        return None, None
    return ECOSYSTEM_ALIASES.get(key, (None, None))

normalize_text(text)

Normalize text for deterministic quote matching.

Applies Unicode NFKC normalization, strips zero-width characters, folds typographic quotes and dashes into ASCII equivalents, collapses whitespace, and case-folds.

Parameters:

Name Type Description Default
text str

Untrusted article or quote text.

required

Returns:

Type Description
str

Normalized lowercase string suitable for deterministic substring lookup.

Source code in src/zerobom/verify/grounding.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def normalize_text(text: str) -> str:
    """Normalize text for deterministic quote matching.

    Applies Unicode NFKC normalization, strips zero-width characters, folds typographic quotes
    and dashes into ASCII equivalents, collapses whitespace, and case-folds.

    Args:
        text: Untrusted article or quote text.

    Returns:
        Normalized lowercase string suitable for deterministic substring lookup.
    """
    normalized = unicodedata.normalize("NFKC", text)
    normalized = _ZERO_WIDTH_RE.sub("", normalized)
    normalized = normalized.translate(_CHAR_NORMALIZATION)
    normalized = _WHITESPACE_RE.sub(" ", normalized).strip().casefold()
    return normalized

parse_ecosystem_version(ecosystem, version_str)

Parse a version string using the ecosystem's native univers Version class.

Parameters:

Name Type Description Default
ecosystem str

Ecosystem alias, canonical PURL type, or OSV ecosystem name.

required
version_str str

Untrusted version string to parse.

required

Returns:

Type Description
Any

An ecosystem-native univers version object supporting ordering comparisons.

Raises:

Type Description
ValueError

If the version contains control characters or whitespace, exceeds MAX_VERSION_LENGTH, the ecosystem is unsupported, or univers rejects it.

Source code in src/zerobom/verify/osv_compiler.py
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
def parse_ecosystem_version(ecosystem: str, version_str: str) -> Any:
    """Parse a version string using the ecosystem's native ``univers`` Version class.

    Args:
        ecosystem: Ecosystem alias, canonical PURL type, or OSV ecosystem name.
        version_str: Untrusted version string to parse.

    Returns:
        An ecosystem-native ``univers`` version object supporting ordering comparisons.

    Raises:
        ValueError: If the version contains control characters or whitespace, exceeds
            ``MAX_VERSION_LENGTH``, the ecosystem is unsupported, or ``univers`` rejects it.
    """
    if _has_control_chars(version_str):
        raise ValueError("Version string must not contain control characters")
    cleaned = version_str.strip()
    if len(cleaned) > MAX_VERSION_LENGTH:
        raise ValueError(f"Version string exceeds maximum length of {MAX_VERSION_LENGTH} chars")
    if not cleaned or any(ch.isspace() for ch in cleaned):
        raise ValueError(f"Invalid empty or whitespace version string: {version_str!r}")
    range_cls = _get_range_class(ecosystem)
    version_cls = range_cls.version_class
    try:
        return version_cls(cleaned)
    except (InvalidVersion, ValueError, TypeError) as exc:
        raise ValueError(f"Invalid version {cleaned!r} for ecosystem {ecosystem!r}: {exc}") from exc

parse_osv_ecosystem(osv_ecosystem)

Split an OSV ecosystem string into (base_ecosystem, normalized_distro_release).

Parameters:

Name Type Description Default
osv_ecosystem str

OSV ecosystem string (e.g., "Debian:11", "Alpine:v3.19", "PyPI").

required

Returns:

Type Description
tuple[str, str | None]

Tuple containing the base ecosystem name and optional normalized distro release.

Source code in src/zerobom/verify/osv_compiler.py
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
def parse_osv_ecosystem(osv_ecosystem: str) -> tuple[str, str | None]:
    """Split an OSV ecosystem string into ``(base_ecosystem, normalized_distro_release)``.

    Args:
        osv_ecosystem: OSV ecosystem string (e.g., ``"Debian:11"``, ``"Alpine:v3.19"``,
            ``"PyPI"``).

    Returns:
        Tuple containing the base ecosystem name and optional normalized distro release.
    """
    cleaned = osv_ecosystem.strip()
    if ":" in cleaned:
        base_part, release_part = cleaned.split(":", 1)
        rel_clean = release_part.strip()
        purl_type, canonical_base = normalize_ecosystem(base_part)
        if purl_type in {"deb", "rpm", "apk"} and canonical_base is not None:
            family_hint = "rhel" if purl_type == "rpm" and "red" in base_part.lower() else base_part
            family_slug = family_hint.strip().lower()
            rel_norm = re.sub(r"[\s_:]+", "-", rel_clean.lower())
            el_match = (
                re.match(r"^el(\d+(?:[._]\d+)*)$", rel_clean, re.IGNORECASE)
                if purl_type == "rpm"
                else None
            )
            if (
                "enterprise_linux" in rel_clean.lower()
                or _DISTRO_FAMILY_RE.match(rel_norm)
                or rel_norm.startswith(f"{family_slug}-")
            ):
                candidate = rel_clean
            elif el_match is not None:
                el_release = el_match.group(1).replace("_", ".")
                candidate = f"{family_hint.strip()}-{el_release}"
            else:
                candidate = f"{family_hint.strip()}-{rel_clean}"
            return canonical_base, normalize_distro_qualifier(candidate)
        if purl_type is None and base_part.strip() and rel_clean:
            rel_norm = re.sub(r"[\s_:]+", "-", rel_clean.lower())
            base_slug = base_part.strip().lower()
            if rel_norm.startswith(f"{base_slug}-"):
                return base_part.strip(), normalize_distro_qualifier(rel_clean)
            return base_part.strip(), normalize_distro_qualifier(f"{base_part.strip()}-{rel_clean}")
    return cleaned, None

parse_version_constraint(ecosystem, constraint, *, package_name=None)

Deterministically parse and validate a :class:VersionConstraint for an ecosystem.

Parameters:

Name Type Description Default
ecosystem str

Ecosystem alias, canonical PURL type, or OSV ecosystem name.

required
constraint VersionConstraint

Structured raw constraint to validate and compile.

required
package_name str | None

Optional canonical package name used to strip redundant NVR prefixes.

None

Returns:

Name Type Description
A ParsedConstraint

class:ParsedConstraint containing validated OSV events or an exact version.

Source code in src/zerobom/verify/osv_compiler.py
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
def parse_version_constraint(
    ecosystem: str,
    constraint: VersionConstraint,
    *,
    package_name: str | None = None,
) -> ParsedConstraint:
    """Deterministically parse and validate a :class:`VersionConstraint` for an ecosystem.

    Args:
        ecosystem: Ecosystem alias, canonical PURL type, or OSV ecosystem name.
        constraint: Structured raw constraint to validate and compile.
        package_name: Optional canonical package name used to strip redundant NVR prefixes.

    Returns:
        A :class:`ParsedConstraint` containing validated OSV events or an exact version.
    """
    try:
        _get_range_class(ecosystem)
    except ValueError as exc:
        return ParsedConstraint(
            events=(),
            exact_version=None,
            is_bounded=False,
            is_valid=False,
            reason=str(exc),
        )

    if constraint.exact is not None:
        exact_clean = _normalize_bound_version(constraint.exact, package_name)
        try:
            parse_ecosystem_version(ecosystem, exact_clean)
        except ValueError as exc:
            return ParsedConstraint(
                events=(),
                exact_version=None,
                is_bounded=False,
                is_valid=False,
                reason=str(exc),
            )
        return ParsedConstraint(
            events=(),
            exact_version=exact_clean,
            is_bounded=True,
            is_valid=True,
        )

    if constraint.is_unbounded:
        intro = (
            _normalize_bound_version(constraint.introduced, package_name)
            if constraint.introduced is not None
            else "0"
        )
        if intro != "0":
            try:
                parse_ecosystem_version(ecosystem, intro)
            except ValueError as exc:
                return ParsedConstraint(
                    events=(),
                    exact_version=None,
                    is_bounded=False,
                    is_valid=False,
                    reason=str(exc),
                )
        return ParsedConstraint(
            events=(OsvRangeEvent(introduced=intro),),
            exact_version=None,
            is_bounded=False,
            is_valid=True,
        )

    if (
        constraint.introduced is not None
        or constraint.fixed is not None
        or constraint.last_affected is not None
    ):
        return _build_interval_parsed_constraint(
            ecosystem,
            introduced=constraint.introduced if constraint.introduced is not None else "0",
            fixed=constraint.fixed,
            last_affected=constraint.last_affected,
            package_name=package_name,
        )

    if constraint.raw_specifier is not None:
        return _parse_raw_specifier(
            ecosystem,
            constraint.raw_specifier,
            package_name=package_name,
        )

    return ParsedConstraint(
        events=(),
        exact_version=None,
        is_bounded=False,
        is_valid=False,
        reason="VersionConstraint contained no parseable version fields.",
    )

resolve_purl(target, ecosystem=None, namespace=None, *, registry_checker=None)

resolve_purl(
    target: ExtractedPackageClaim,
    ecosystem: str | None = None,
    namespace: str | None = None,
    *,
    registry_checker: RegistryChecker | None = None,
) -> PurlResolutionResult
resolve_purl(
    target: str,
    ecosystem: str | None = None,
    namespace: str | None = None,
    *,
    registry_checker: RegistryChecker | None = None,
) -> PurlResolutionResult

Resolve a raw package claim or fuzzy name to a canonical PURL.

Applies ecosystem normalization, generic-name blocking (without allowing OS distro defaults to bypass the blocklist), strict traversal/injection coordinate validation, and optional upstream registry existence checking.

Parameters:

Name Type Description Default
target ExtractedPackageClaim | str

Either an :class:ExtractedPackageClaim or a raw package/PURL string.

required
ecosystem str | None

Optional ecosystem hint overriding target.ecosystem.

None
namespace str | None

Optional namespace/scope/groupId overriding target.namespace.

None
registry_checker RegistryChecker | None

Optional :class:RegistryChecker (defaults to offline None).

None

Returns:

Name Type Description
A PurlResolutionResult

class:PurlResolutionResult with canonical PURL, validity flags, and diagnostics.

Source code in src/zerobom/verify/purl.py
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
def resolve_purl(
    target: ExtractedPackageClaim | str,
    ecosystem: str | None = None,
    namespace: str | None = None,
    *,
    registry_checker: RegistryChecker | None = None,
) -> PurlResolutionResult:
    """Resolve a raw package claim or fuzzy name to a canonical PURL.

    Applies ecosystem normalization, generic-name blocking (without allowing OS distro defaults
    to bypass the blocklist), strict traversal/injection coordinate validation, and optional
    upstream registry existence checking.

    Args:
        target: Either an :class:`ExtractedPackageClaim` or a raw package/PURL string.
        ecosystem: Optional ecosystem hint overriding ``target.ecosystem``.
        namespace: Optional namespace/scope/groupId overriding ``target.namespace``.
        registry_checker: Optional :class:`RegistryChecker` (defaults to offline ``None``).

    Returns:
        A :class:`PurlResolutionResult` with canonical PURL, validity flags, and diagnostics.
    """
    if isinstance(target, ExtractedPackageClaim):
        raw_name = target.raw_package_name
        eco_input = ecosystem if ecosystem is not None else target.ecosystem
        ns_input = namespace if namespace is not None else target.namespace
    else:
        raw_name = target
        eco_input = ecosystem
        ns_input = namespace

    if _has_control_chars(raw_name) or (ns_input is not None and _has_control_chars(ns_input)):
        return PurlResolutionResult(
            canonical_purl=None,
            ecosystem=None,
            osv_ecosystem=None,
            is_valid=False,
            reasons=("Package identifier or namespace contains control characters.",),
        )

    stripped_raw = raw_name.strip()
    if not stripped_raw:
        return PurlResolutionResult(
            canonical_purl=None,
            ecosystem=None,
            osv_ecosystem=None,
            is_valid=False,
            reasons=("Package name is empty.",),
        )

    if len(stripped_raw) > MAX_PACKAGE_INPUT_LENGTH or (
        ns_input is not None and len(ns_input) > MAX_PACKAGE_INPUT_LENGTH
    ):
        return PurlResolutionResult(
            canonical_purl=None,
            ecosystem=None,
            osv_ecosystem=None,
            is_valid=False,
            reasons=(f"Package input exceeds {MAX_PACKAGE_INPUT_LENGTH} characters.",),
        )

    # Path A: Input is already formatted as a Package URL (pkg:...).
    if stripped_raw.startswith("pkg:"):
        try:
            parsed = PackageURL.from_string(stripped_raw)
        except ValueError as exc:
            return PurlResolutionResult(
                canonical_purl=None,
                ecosystem=None,
                osv_ecosystem=None,
                is_valid=False,
                reasons=(f"Malformed PURL '{stripped_raw}': {exc}",),
            )
        purl_type, hinted_osv = normalize_ecosystem(parsed.type)
        if purl_type is None:
            return PurlResolutionResult(
                canonical_purl=None,
                ecosystem=parsed.type,
                osv_ecosystem=None,
                is_valid=False,
                reasons=(f"Unsupported PURL ecosystem '{parsed.type}'.",),
            )
        ns_hint = parsed.namespace or ns_input
        osv_ecosystem = _resolve_osv_ecosystem(purl_type, ns_hint, hinted_osv)
        norm_ns, norm_name, ns_is_distro = _split_namespace_and_name(
            purl_type=purl_type,
            cleaned_name=parsed.name,
            explicit_namespace=ns_hint,
            osv_ecosystem=osv_ecosystem,
        )
    else:
        # Path B: Fuzzy / natural-language package name + optional ecosystem hint.
        cleaned_name, inferred_eco = _strip_natural_language(stripped_raw)
        purl_type, hinted_osv = normalize_ecosystem(eco_input or inferred_eco)
        if purl_type == "generic" and (
            cleaned_name.lower().startswith("golang.org/")
            or (ns_input or "").strip().lower().startswith("golang.org/")
        ):
            purl_type, hinted_osv = ("golang", "Go")
        if purl_type is None:
            return PurlResolutionResult(
                canonical_purl=None,
                ecosystem=eco_input or inferred_eco,
                osv_ecosystem=None,
                is_valid=False,
                reasons=("Could not determine canonical ecosystem for package claim.",),
            )
        osv_ecosystem = _resolve_osv_ecosystem(purl_type, ns_input, hinted_osv)
        norm_ns, norm_name, ns_is_distro = _split_namespace_and_name(
            purl_type=purl_type,
            cleaned_name=cleaned_name,
            explicit_namespace=ns_input,
            osv_ecosystem=osv_ecosystem,
        )

    distro_ns_invalid = (
        purl_type in _DISTRO_PURL_TYPES
        and norm_ns is not None
        and (not _DISTRO_NAMESPACE_RE.match(norm_ns) or norm_ns in _NON_DISTRO_NAMESPACE_BLOCKLIST)
    )
    if (
        distro_ns_invalid
        or not _validate_coordinate_safety(norm_name)
        or (norm_ns is not None and not _validate_coordinate_safety(norm_ns))
    ):
        return PurlResolutionResult(
            canonical_purl=None,
            ecosystem=purl_type,
            osv_ecosystem=osv_ecosystem,
            namespace=norm_ns,
            name=norm_name or None,
            is_valid=False,
            reasons=(
                f"Rejected unsafe or malformed package coordinates (ns={norm_ns!r}, "
                f"name={norm_name!r}).",
            ),
        )

    # Auto-assigned OS distro namespaces and pkg:generic/ namespaces must not bypass
    # always-generic blocklist words such as 'utils' or 'core'. Runtime names ('kernel',
    # 'ruby') are blocked on package registries but permitted on OS/generic ecosystems.
    has_explicit_package_ns = norm_ns is not None and not ns_is_distro and purl_type != "generic"
    is_single_char = len(norm_name) <= 1
    lowered_name = norm_name.lower()
    is_always_generic = lowered_name in GENERIC_PACKAGE_BLOCKLIST
    is_registry_only_generic = (
        lowered_name in REGISTRY_ONLY_GENERIC_BLOCKLIST
        and purl_type not in _RUNTIME_FRIENDLY_PURL_TYPES
    )

    if is_single_char or (
        (is_always_generic or is_registry_only_generic) and not has_explicit_package_ns
    ):
        return PurlResolutionResult(
            canonical_purl=None,
            ecosystem=purl_type,
            osv_ecosystem=osv_ecosystem,
            namespace=norm_ns,
            name=norm_name,
            is_valid=False,
            is_blocked_generic=True,
            reasons=(
                f"Blocked overly generic or single-character package name '{norm_name}' "
                f"for ecosystem '{purl_type}' without an explicit package namespace.",
            ),
        )

    try:
        canonical_purl = _build_canonical_purl(purl_type, norm_ns, norm_name)
    except ValueError as exc:
        return PurlResolutionResult(
            canonical_purl=None,
            ecosystem=purl_type,
            osv_ecosystem=osv_ecosystem,
            namespace=norm_ns,
            name=norm_name,
            is_valid=False,
            reasons=(f"Failed to construct canonical PURL: {exc}",),
        )

    registry_status = RegistryStatus.SKIPPED
    reasons: list[str] = []
    is_valid = True

    if registry_checker is not None:
        registry_status = registry_checker.check(canonical_purl)
        if registry_status == RegistryStatus.NOT_FOUND:
            is_valid = False
            reasons.append(f"Package '{canonical_purl}' was not found in upstream registry (404).")
        elif registry_status == RegistryStatus.ERROR:
            reasons.append(
                f"Upstream registry lookup errored for '{canonical_purl}'; "
                "continuing without rejecting."
            )

    return PurlResolutionResult(
        canonical_purl=canonical_purl,
        ecosystem=purl_type,
        osv_ecosystem=osv_ecosystem,
        namespace=norm_ns,
        name=norm_name,
        is_valid=is_valid,
        is_blocked_generic=False,
        registry_status=registry_status,
        reasons=tuple(reasons),
    )

route_score(composite_score)

Deterministically map a composite score to AUTO, TRIAGE, or DROP.

Parameters:

Name Type Description Default
composite_score float

Two-axis credibility score in [0.0, 1.0].

required

Returns:

Type Description
RoutingDecision

class:RoutingDecision corresponding to the threshold bands.

Source code in src/zerobom/verify/scorer.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def route_score(composite_score: float) -> RoutingDecision:
    """Deterministically map a composite score to ``AUTO``, ``TRIAGE``, or ``DROP``.

    Args:
        composite_score: Two-axis credibility score in ``[0.0, 1.0]``.

    Returns:
        :class:`RoutingDecision` corresponding to the threshold bands.
    """
    if composite_score >= AUTO_THRESHOLD:
        return RoutingDecision.AUTO
    if composite_score >= TRIAGE_THRESHOLD:
        return RoutingDecision.TRIAGE
    return RoutingDecision.DROP

score_claim(claim, grounding, purl, *, source_tier, has_valid_version_range, has_bounded_version_range, has_advisory_technical_context=False, extra_reasons=())

Compute extraction_specificity, composite_score, and routing for one claim.

Parameters:

Name Type Description Default
claim ExtractedPackageClaim

Extracted package claim under evaluation.

required
grounding GroundingResult

Output from :func:verify_quote_grounding.

required
purl PurlResolutionResult

Output from :func:resolve_purl.

required
source_tier SourceTier

Publisher credibility tier from the parent :class:RawArticle.

required
has_valid_version_range bool

True when all version constraints parsed cleanly.

required
has_bounded_version_range bool

True when at least one valid bounded or exact constraint exists.

required
has_advisory_technical_context bool

True if the advisory includes CWEs, aliases, or refs.

False
extra_reasons tuple[str, ...]

Additional diagnostic messages (e.g., version parser errors).

()

Returns:

Name Type Description
A ClaimVerificationResult

class:ClaimVerificationResult detailing scores, routing, and diagnostics.

Source code in src/zerobom/verify/scorer.py
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
def score_claim(
    claim: ExtractedPackageClaim,
    grounding: GroundingResult,
    purl: PurlResolutionResult,
    *,
    source_tier: SourceTier,
    has_valid_version_range: bool,
    has_bounded_version_range: bool,
    has_advisory_technical_context: bool = False,
    extra_reasons: tuple[str, ...] = (),
) -> ClaimVerificationResult:
    """Compute ``extraction_specificity``, ``composite_score``, and routing for one claim.

    Args:
        claim: Extracted package claim under evaluation.
        grounding: Output from :func:`verify_quote_grounding`.
        purl: Output from :func:`resolve_purl`.
        source_tier: Publisher credibility tier from the parent :class:`RawArticle`.
        has_valid_version_range: True when all version constraints parsed cleanly.
        has_bounded_version_range: True when at least one valid bounded or exact constraint exists.
        has_advisory_technical_context: True if the advisory includes CWEs, aliases, or refs.
        extra_reasons: Additional diagnostic messages (e.g., version parser errors).

    Returns:
        A :class:`ClaimVerificationResult` detailing scores, routing, and diagnostics.
    """
    tier_weight = TIER_WEIGHTS[source_tier]
    reasons: list[str] = list(purl.reasons) + list(grounding.reasons) + list(extra_reasons)

    # Hard-reject gate: fail closed on invalid PURL, blocked generic package, or confirmed 404.
    if (
        not purl.is_valid
        or purl.is_blocked_generic
        or purl.registry_status == RegistryStatus.NOT_FOUND
    ):
        return ClaimVerificationResult(
            claim=claim,
            grounding=grounding,
            purl=purl,
            has_valid_version_range=has_valid_version_range,
            has_bounded_version_range=has_bounded_version_range,
            extraction_specificity=0.0,
            composite_score=0.0,
            routing=RoutingDecision.DROP,
            reasons=tuple(reasons),
        )

    # Additive extraction_specificity rubric.
    specificity = 0.25  # Canonical non-generic PURL resolved

    if has_valid_version_range and has_bounded_version_range:
        specificity += 0.35
    elif has_valid_version_range:
        specificity += 0.10

    if grounding.status == GroundingStatus.VERIFIED:
        specificity += 0.30
    elif grounding.status == GroundingStatus.QUOTE_ONLY_WEAK:
        specificity += 0.15

    # Offline (SKIPPED) registry checks keep a neutral 0.05 baseline so offline runs still
    # operate cleanly while confirmed registry hits earn 0.10. Registry lookup errors fail
    # closed at 0.0 corroboration points and are capped below AUTO below.
    if purl.registry_status == RegistryStatus.EXISTS:
        registry_points = 0.10
    elif purl.registry_status == RegistryStatus.ERROR:
        registry_points = 0.0
    else:
        registry_points = 0.05
    technical_points = (
        0.05 if (claim.fix_commit_url or claim.poc_url or has_advisory_technical_context) else 0.0
    )
    specificity += min(0.10, registry_points + technical_points)

    specificity = max(0.0, min(1.0, specificity))

    # Hard grounding, unbounded-range, and registry-error caps prevent ungrounded/unbounded
    # claims or unverified registry outages from reaching AUTO alerting.
    if grounding.status == GroundingStatus.UNGROUNDED:
        specificity = min(specificity * 0.35, UNGROUNDED_SPECIFICITY_CAP)
        reasons.append("Capped specificity below DROP threshold due to ungrounded quote.")
    elif grounding.status == GroundingStatus.QUOTE_ONLY_WEAK:
        specificity = min(specificity, WEAK_GROUNDING_SPECIFICITY_CAP)
        reasons.append(
            "Capped specificity below AUTO threshold due to weak quote grounding "
            "(missing package or version tokens inside quote)."
        )

    if not has_bounded_version_range:
        specificity = min(specificity, UNBOUNDED_VERSION_SPECIFICITY_CAP)
        reasons.append(
            "Capped specificity below AUTO threshold because version constraints lack a "
            "bounded or exact fix range."
        )

    if purl.registry_status == RegistryStatus.ERROR:
        specificity = min(specificity, REGISTRY_ERROR_SPECIFICITY_CAP)
        reasons.append(
            "Capped specificity below AUTO threshold due to upstream registry lookup error."
        )

    extraction_specificity = round(specificity, 4)
    composite_score = round(tier_weight * extraction_specificity, 4)
    routing = route_score(composite_score)

    return ClaimVerificationResult(
        claim=claim,
        grounding=grounding,
        purl=purl,
        has_valid_version_range=has_valid_version_range,
        has_bounded_version_range=has_bounded_version_range,
        extraction_specificity=extraction_specificity,
        composite_score=composite_score,
        routing=routing,
        reasons=tuple(reasons),
    )

strip_package_nvr_prefix(version_str, package_name)

Strip a redundant <package_name>- NVR prefix when followed by an ASCII digit.

For example, converts RPM/DEB build NVR strings such as kernel-5.14.0-687.60.1.el9_8 (given package_name="kernel") into 5.14.0-687.60.1.el9_8. Unrelated strings or non-digit suffixes are returned trimmed and unmodified.

Parameters:

Name Type Description Default
version_str str

Raw extracted version or NVR token.

required
package_name str | None

Canonical package name associated with the claim.

required

Returns:

Type Description
str

Normalized version string with redundant package-name prefix stripped if valid.

Source code in src/zerobom/verify/osv_compiler.py
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
def strip_package_nvr_prefix(version_str: str, package_name: str | None) -> str:
    """Strip a redundant ``<package_name>-`` NVR prefix when followed by an ASCII digit.

    For example, converts RPM/DEB build NVR strings such as
    ``kernel-5.14.0-687.60.1.el9_8`` (given ``package_name="kernel"``) into
    ``5.14.0-687.60.1.el9_8``. Unrelated strings or non-digit suffixes are returned
    trimmed and unmodified.

    Args:
        version_str: Raw extracted version or NVR token.
        package_name: Canonical package name associated with the claim.

    Returns:
        Normalized version string with redundant package-name prefix stripped if valid.
    """
    cleaned = version_str.strip()
    if not cleaned or not package_name:
        return cleaned
    pkg = package_name.strip().lower()
    if not pkg:
        return cleaned
    prefix = f"{pkg}-"
    if cleaned.lower().startswith(prefix):
        remainder = cleaned[len(prefix) :]
        if remainder and remainder[0].isdigit():
            return remainder
    return cleaned

validate_claim_versions(ecosystem, constraints, *, package_name=None)

Validate all version constraints for a claim and report validity and boundedness.

Parameters:

Name Type Description Default
ecosystem str | None

Canonical PURL ecosystem type or OSV ecosystem name.

required
constraints Sequence[VersionConstraint]

Sequence of constraints attached to a package claim.

required
package_name str | None

Optional canonical package name used to strip redundant NVR prefixes.

None

Returns:

Type Description
tuple[bool, bool, tuple[str, ...]]

Tuple of (has_valid_version_range, has_bounded_version_range, failure_reasons).

Source code in src/zerobom/verify/osv_compiler.py
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
def validate_claim_versions(
    ecosystem: str | None,
    constraints: Sequence[VersionConstraint],
    *,
    package_name: str | None = None,
) -> tuple[bool, bool, tuple[str, ...]]:
    """Validate all version constraints for a claim and report validity and boundedness.

    Args:
        ecosystem: Canonical PURL ecosystem type or OSV ecosystem name.
        constraints: Sequence of constraints attached to a package claim.
        package_name: Optional canonical package name used to strip redundant NVR prefixes.

    Returns:
        Tuple of ``(has_valid_version_range, has_bounded_version_range, failure_reasons)``.
    """
    if not constraints:
        return False, False, ("No version constraints provided.",)
    if ecosystem is None:
        return False, False, ("Ecosystem is unknown; cannot validate versions.",)

    try:
        _get_range_class(ecosystem)
    except ValueError as exc:
        return False, False, (str(exc),)

    parsed = [
        parse_version_constraint(ecosystem, item, package_name=package_name) for item in constraints
    ]
    reasons = tuple(item.reason for item in parsed if not item.is_valid and item.reason)
    all_valid = all(item.is_valid for item in parsed)
    has_bounded = all_valid and any(item.is_bounded for item in parsed)
    return all_valid, has_bounded, reasons

verify_advisory(article, advisory, *, registry_checker=None)

Run deterministic PURL, grounding, version, polarity, and credibility scoring.

Parameters:

Name Type Description Default
article RawArticle

Raw ingested security article supplying body text and source tier.

required
advisory ExtractedAdvisory

Extracted candidate advisory containing package vulnerability claims.

required
registry_checker RegistryChecker | None

Optional upstream :class:RegistryChecker (defaults to offline None).

None

Returns:

Name Type Description
A CredibilityReport

class:CredibilityReport partitioning claims into accepted_claims and

CredibilityReport

dropped_claims along with advisory-level routing.

Source code in src/zerobom/verify/scorer.py
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
def verify_advisory(
    article: RawArticle,
    advisory: ExtractedAdvisory,
    *,
    registry_checker: RegistryChecker | None = None,
) -> CredibilityReport:
    """Run deterministic PURL, grounding, version, polarity, and credibility scoring.

    Args:
        article: Raw ingested security article supplying body text and source tier.
        advisory: Extracted candidate advisory containing package vulnerability claims.
        registry_checker: Optional upstream :class:`RegistryChecker` (defaults to offline ``None``).

    Returns:
        A :class:`CredibilityReport` partitioning claims into ``accepted_claims`` and
        ``dropped_claims`` along with advisory-level routing.
    """
    tier_weight = TIER_WEIGHTS[article.source_tier]

    if advisory.article_type in _DROP_ARTICLE_TYPES:
        return CredibilityReport(
            article_url=advisory.article_url,
            source_tier=article.source_tier,
            source_tier_weight=tier_weight,
            extraction_specificity=0.0,
            composite_score=0.0,
            routing=RoutingDecision.DROP,
            claim_results=(),
            accepted_claims=(),
            dropped_claims=(),
            reasons=(
                f"Dropped advisory classified as non-actionable '{advisory.article_type.value}'.",
            ),
        )

    grounding_corpus = f"{article.title}\n{article.body}\n{article.url}".casefold()
    grounded_cwe = _has_grounded_cwe(advisory.cwe_ids, grounding_corpus)
    has_tech_context = bool(
        grounded_cwe
        or advisory.references
        or advisory.known_aliases
        or any(claim.claim_aliases for claim in advisory.claims)
    )

    if not advisory.claims:
        return CredibilityReport(
            article_url=advisory.article_url,
            source_tier=article.source_tier,
            source_tier_weight=tier_weight,
            extraction_specificity=0.0,
            composite_score=0.0,
            routing=RoutingDecision.DROP,
            claim_results=(),
            accepted_claims=(),
            dropped_claims=(),
            reasons=("Advisory contains no package vulnerability claims.",),
        )

    claim_results: list[ClaimVerificationResult] = []
    for claim in advisory.claims:
        purl_res = resolve_purl(claim, registry_checker=registry_checker)
        grounding_res = verify_quote_grounding(
            article.body,
            claim,
            canonical_package_name=purl_res.name,
        )
        has_valid_ver, has_bounded_ver, ver_reasons = validate_claim_versions(
            purl_res.ecosystem,
            claim.version_constraints,
            package_name=purl_res.name,
        )
        scored = score_claim(
            claim,
            grounding_res,
            purl_res,
            source_tier=article.source_tier,
            has_valid_version_range=has_valid_ver,
            has_bounded_version_range=has_bounded_ver,
            has_advisory_technical_context=has_tech_context,
            extra_reasons=ver_reasons,
        )
        if scored.routing != RoutingDecision.DROP:
            cap_reasons: list[str] = []
            polarity_ok, polarity_reasons = check_quote_polarity(claim)
            if not polarity_ok:
                cap_reasons.extend(polarity_reasons)
            distro_ok, distro_reasons = check_distro_quote_grounding(
                claim,
                ecosystem=purl_res.ecosystem,
                namespace=purl_res.namespace,
            )
            if not distro_ok:
                cap_reasons.extend(distro_reasons)
            has_overlap, overlap_reason = detect_overlapping_branch_ranges(
                purl_res.ecosystem,
                claim.version_constraints,
                package_name=purl_res.name,
            )
            if has_overlap and overlap_reason:
                cap_reasons.append(overlap_reason)
            if (
                advisory.article_type in _TRIAGE_ONLY_ARTICLE_TYPES
                and advisory.article_type is not None
            ):
                cap_reasons.append(
                    f"Capped specificity below AUTO threshold for secondary article type "
                    f"'{advisory.article_type.value}'."
                )
            scored = _apply_triage_cap(scored, tier_weight=tier_weight, extra_reasons=cap_reasons)
        claim_results.append(scored)

    # Detect multi-claim open-origin ("introduced='0'") overlaps across separate claims targeting
    # the same canonical PURL and formatted ecosystem stream (e.g. OpenSSL 5-branch updates).
    grouped_indices: dict[tuple[str, str], list[int]] = {}
    for idx, cr in enumerate(claim_results):
        if cr.routing == RoutingDecision.DROP:
            continue
        if (
            cr.purl.canonical_purl is None
            or cr.purl.osv_ecosystem is None
            or cr.purl.ecosystem is None
        ):
            continue
        formatted_eco = _format_claim_osv_ecosystem(
            cr.purl.osv_ecosystem,
            cr.purl.ecosystem,
            cr.claim.distro_release,
        )
        grouped_indices.setdefault((cr.purl.canonical_purl, formatted_eco), []).append(idx)

    for indices in grouped_indices.values():
        if len(indices) < 2:
            continue
        first = claim_results[indices[0]]
        combined_constraints: list[VersionConstraint] = [
            constraint
            for idx in indices
            for constraint in claim_results[idx].claim.version_constraints
        ]
        has_group_overlap, group_overlap_reason = detect_overlapping_branch_ranges(
            first.purl.ecosystem,
            combined_constraints,
            package_name=first.purl.name,
        )
        if has_group_overlap and group_overlap_reason:
            for idx in indices:
                claim_results[idx] = _apply_triage_cap(
                    claim_results[idx],
                    tier_weight=tier_weight,
                    extra_reasons=(group_overlap_reason,),
                )

    accepted = tuple(cr for cr in claim_results if cr.routing != RoutingDecision.DROP)
    dropped = tuple(cr for cr in claim_results if cr.routing == RoutingDecision.DROP)

    pool = accepted if accepted else tuple(claim_results)
    top_claim = max(pool, key=lambda cr: cr.composite_score)
    advisory_specificity = top_claim.extraction_specificity
    advisory_composite = top_claim.composite_score
    advisory_routing = route_score(advisory_composite)

    advisory_reasons: list[str] = []
    if not accepted:
        advisory_reasons.append("All extracted package claims were dropped during verification.")
    elif dropped:
        advisory_reasons.append(
            f"Accepted {len(accepted)} claim(s); dropped {len(dropped)} unverified claim(s)."
        )

    return CredibilityReport(
        article_url=advisory.article_url,
        source_tier=article.source_tier,
        source_tier_weight=tier_weight,
        extraction_specificity=advisory_specificity,
        composite_score=advisory_composite,
        routing=advisory_routing,
        claim_results=tuple(claim_results),
        accepted_claims=accepted,
        dropped_claims=dropped,
        reasons=tuple(advisory_reasons),
    )

verify_quote_grounding(article_body, claim, *, canonical_package_name=None, min_quote_length=MIN_QUOTE_LENGTH, min_quote_tokens=MIN_QUOTE_TOKENS)

Verify extracted evidence quote(s) against the raw article text in two stages.

Checks claim.evidence_quote and every entry in claim.supporting_quotes. All quotes must pass Stage 1 substring grounding, and at least one single verified quote must mention both a package token and a claimed version token (preventing cross-paragraph bait-and-switch).

Parameters:

Name Type Description Default
article_body str

Raw plain-text body of the ingested article.

required
claim ExtractedPackageClaim

Extracted package claim containing evidence_quote, optional supporting_quotes, and constraints.

required
canonical_package_name str | None

Optional canonical PURL name to broaden valid aliases.

None
min_quote_length int

Minimum normalized character count required to prevent trivial matches.

MIN_QUOTE_LENGTH
min_quote_tokens int

Minimum whitespace-delimited word count required in each quote.

MIN_QUOTE_TOKENS

Returns:

Name Type Description
A GroundingResult

class:GroundingResult classifying the claim as VERIFIED,

GroundingResult

QUOTE_ONLY_WEAK, or UNGROUNDED.

Raises:

Type Description
ValueError

If min_quote_length < 1 or min_quote_tokens < 1.

Source code in src/zerobom/verify/grounding.py
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
def verify_quote_grounding(
    article_body: str,
    claim: ExtractedPackageClaim,
    *,
    canonical_package_name: str | None = None,
    min_quote_length: int = MIN_QUOTE_LENGTH,
    min_quote_tokens: int = MIN_QUOTE_TOKENS,
) -> GroundingResult:
    """Verify extracted evidence quote(s) against the raw article text in two stages.

    Checks ``claim.evidence_quote`` and every entry in ``claim.supporting_quotes``. All quotes
    must pass Stage 1 substring grounding, and at least one single verified quote must mention
    both a package token and a claimed version token (preventing cross-paragraph bait-and-switch).

    Args:
        article_body: Raw plain-text body of the ingested article.
        claim: Extracted package claim containing ``evidence_quote``, optional
            ``supporting_quotes``, and constraints.
        canonical_package_name: Optional canonical PURL ``name`` to broaden valid aliases.
        min_quote_length: Minimum normalized character count required to prevent trivial matches.
        min_quote_tokens: Minimum whitespace-delimited word count required in each quote.

    Returns:
        A :class:`GroundingResult` classifying the claim as ``VERIFIED``,
        ``QUOTE_ONLY_WEAK``, or ``UNGROUNDED``.

    Raises:
        ValueError: If ``min_quote_length < 1`` or ``min_quote_tokens < 1``.
    """
    if min_quote_length < 1:
        raise ValueError("min_quote_length must be >= 1")
    if min_quote_tokens < 1:
        raise ValueError("min_quote_tokens must be >= 1")

    all_quotes = (claim.evidence_quote, *claim.supporting_quotes)
    norm_body: str | None = None
    norm_quotes: list[str] = []
    primary_span: tuple[int, int] | None = None
    all_exact = True

    for idx, quote in enumerate(all_quotes):
        ok, match_type, span, norm_q, norm_body, err_reason = _match_single_quote_stage1(
            article_body,
            quote,
            norm_body=norm_body,
            min_quote_length=min_quote_length,
            min_quote_tokens=min_quote_tokens,
            is_primary=(idx == 0),
        )
        if not ok:
            return GroundingResult(
                status=GroundingStatus.UNGROUNDED,
                match_type=GroundingMatchType.NONE,
                quote_found_in_article=False,
                package_token_found=False,
                version_tokens_found=False,
                matched_span=None,
                reasons=(err_reason or "Quote failed grounding.",),
            )
        if idx == 0:
            primary_span = span
        if match_type != GroundingMatchType.EXACT:
            all_exact = False
        norm_quotes.append(norm_q)

    overall_match_type = GroundingMatchType.EXACT if all_exact else GroundingMatchType.NORMALIZED

    # Stage 2: Anti-bait-and-switch check requiring package + version co-occurrence in at least
    # one single verified quote (supporting context quotes only need Stage 1 article grounding).
    candidates = extract_package_match_candidates(
        claim.raw_package_name,
        canonical_package_name=canonical_package_name,
    )
    version_tokens = extract_claim_version_tokens(claim)

    per_quote_flags: list[tuple[bool, bool]] = []
    for norm_q in norm_quotes:
        has_pkg = any(_contains_token_boundary(norm_q, cand) for cand in candidates)
        has_ver = (
            True
            if not version_tokens
            else any(_version_matches_quote(norm_q, token, candidates) for token in version_tokens)
        )
        per_quote_flags.append((has_pkg, has_ver))

    package_token_found = any(has_pkg for has_pkg, _ in per_quote_flags)
    missing_versions = tuple(
        token
        for token in version_tokens
        if not any(_version_matches_quote(norm_q, token, candidates) for norm_q in norm_quotes)
    )
    any_version_found = (
        True if not version_tokens else any(has_ver for _, has_ver in per_quote_flags)
    )
    version_tokens_found = True if not version_tokens else not missing_versions
    has_cooccurring_quote = any(has_pkg and has_ver for has_pkg, has_ver in per_quote_flags)

    if has_cooccurring_quote and not missing_versions:
        return GroundingResult(
            status=GroundingStatus.VERIFIED,
            match_type=overall_match_type,
            quote_found_in_article=True,
            package_token_found=True,
            version_tokens_found=True,
            matched_span=primary_span,
            reasons=(),
        )

    reasons: list[str] = []
    if not package_token_found:
        reasons.append(
            f"Quote matched article text but does not mention package '{claim.raw_package_name}'."
        )
    if not any_version_found:
        reasons.append(
            "Quote matched article text but does not contain any claimed version token "
            f"({', '.join(version_tokens)})."
        )
    elif missing_versions:
        reasons.append(
            "Quote matched article text but is missing claimed version token(s) "
            f"({', '.join(missing_versions)})."
        )
    if package_token_found and any_version_found and not has_cooccurring_quote:
        reasons.append(
            "Package name and version tokens were split across separate quotes without "
            "co-occurring in any single verified quote."
        )

    return GroundingResult(
        status=GroundingStatus.QUOTE_ONLY_WEAK,
        match_type=overall_match_type,
        quote_found_in_article=True,
        package_token_found=package_token_found,
        version_tokens_found=version_tokens_found,
        matched_span=primary_span,
        reasons=tuple(reasons),
    )