# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-scope-a-delegated-credential-when-a-downstream-tool-s-capability-manifest-drifts-mid-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-scope-a-delegated-credential-when-a-downstream-tool-s-capability-manifest-drifts-mid-warrant.warrant.json
# Markdown SHA-256:   057185337416b5c5cee2a5210473e62d82067249d8f9c776dfdc3114ee0c9530
# Code AST SHA-256:   efffcb9f01d2eac7634116837346fb47b7bbe00f34d2df2a061b6e6964f86c50
# Verified Classes:   WarrantScopeDriftError, Warrant
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class WarrantScopeDriftError(RuntimeError):
    """Raised when a downstream capability manifest drifted under a live warrant
    in a way that widens or ambiguously alters the delegated scope."""


@dataclass(frozen=True)
class Warrant:
    capability: str
    manifest_hash_at_mint: str
    constraints: frozenset  # e.g. {"index=public"}


def manifest_hash(manifest: dict) -> str:
    canon = repr(sorted(manifest.items())).encode()
    return hashlib.sha256(canon).hexdigest()


def classify_drift(warrant: Warrant, current_manifest: dict) -> str:
    # Returns "narrowing" | "widening" | "ambiguous".
    # A real implementation diffs parameter sets and enum domains; here we
    # treat any added override parameter as widening.
    added = set(current_manifest.get("params", {})) - set(
        warrant.constraints and {"query"} or set()
    )
    if "index" in current_manifest.get("params", {}) and "index=public" not in warrant.constraints:
        return "widening"
    if added:
        return "ambiguous"
    return "narrowing"


def authorize_invocation(warrant: Warrant, current_manifest: dict) -> None:
    current_hash = manifest_hash(current_manifest)
    if current_hash == warrant.manifest_hash_at_mint:
        return  # pinned binding holds; proceed

    drift = classify_drift(warrant, current_manifest)
    if drift in ("widening", "ambiguous"):
        raise WarrantScopeDriftError(
            f"capability {warrant.capability!r} manifest drifted ({drift}) "
            f"under live warrant; mint_hash={warrant.manifest_hash_at_mint[:12]} "
            f"current_hash={current_hash[:12]}. Re-scope required before invocation."
        )
    # narrowing drift: warrant still bounds the call
    return


# Example: the observed incident reproduced.
w = Warrant(
    capability="search.read",
    manifest_hash_at_mint=manifest_hash({"params": {"query": "string"}}),
    constraints=frozenset({"index=public"}),
)
drifted = {"params": {"query": "string", "index": "string"}}
authorize_invocation(w, drifted)  # raises WarrantScopeDriftError
