# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-aaif-credential-whose-scope-narrows-only-in-natural-language.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-aaif-credential-whose-scope-narrows-only-in-natural-language.warrant.json
# Markdown SHA-256:   1640c51cc3de25a5745533be6d8baac8284cb5fff695050c1001d407c8a9dff1
# Code AST SHA-256:   fcaad3f85dc301d7115ffd88f2749fe443d6de21ad4f2d56d1e017f5f4db456b
# Verified Classes:   DelegationScopeMismatch, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class DelegationScopeMismatch(RuntimeError):
    """Raised when a delegated credential's prose intent narrows authority
    that its machine-readable scope set does not actually narrow."""


# Constraint verbs that, when present in warrant prose, assert a restriction
# the scope set MUST mechanically encode.
CONSTRAINT_MARKERS = (
    "do not", "don't", "read-only", "read only", "only", "except",
    "never", "must not", "without",
)


@dataclass(frozen=True)
class Warrant:
    parent_scopes: FrozenSet[str]
    child_scopes: FrozenSet[str]
    intent: str
    audience: str
    issuer: str = field(default="")


def _scope_covers(parent: str, child: str) -> bool:
    """True if `child` scope is authorized by `parent` scope (wildcard aware)."""
    if parent == child:
        return True
    if parent.endswith(":*"):
        return child.startswith(parent[:-1])
    return False


def _set_contained(parents: FrozenSet[str], children: FrozenSet[str]) -> bool:
    return all(any(_scope_covers(p, c) for p in parents) for c in children)


def _prose_asserts_restriction(intent: str) -> bool:
    low = intent.lower()
    return any(marker in low for marker in CONSTRAINT_MARKERS)


def validate_delegation(w: Warrant) -> None:
    # 1. Set arithmetic: child must be contained in parent. Necessary, not sufficient.
    if not _set_contained(w.parent_scopes, w.child_scopes):
        raise DelegationScopeMismatch(
            f"child scopes {sorted(w.child_scopes)} not contained in "
            f"parent scopes {sorted(w.parent_scopes)}"
        )

    # 2. Intent narrowing must be backed by scope narrowing.
    prose_restricts = _prose_asserts_restriction(w.intent)
    scope_restricts = w.child_scopes < w.parent_scopes  # strict subset

    if prose_restricts and not scope_restricts:
        raise DelegationScopeMismatch(
            f"warrant intent for audience={w.audience!r} asserts a restriction "
            f"({w.intent!r}) but child_scopes equals parent_scopes "
            f"({sorted(w.child_scopes)}). Prose narrowing without scope "
            f"narrowing is an authority-escalation vector: refuse to mint."
        )

    # 3. Wildcard + prose caveat is always unsound: the caveat cannot be enforced.
    wildcard_parent = any(s.endswith(":*") for s in w.parent_scopes)
    if wildcard_parent and prose_restricts:
        raise DelegationScopeMismatch(
            f"parent holds wildcard scopes {sorted(w.parent_scopes)} and warrant "
            f"relies on prose caveat {w.intent!r}; enumerate child scopes instead."
        )


# --- demonstration of the observed failure trace -------------------------

try:
    validate_delegation(
        Warrant(
            parent_scopes=frozenset({"invoices:*"}),
            child_scopes=frozenset({"invoices:read", "invoices:list", "invoices:delete"}),
            intent="Read invoice records to reconcile. Do not mutate.",
            audience="worker-W",
            issuer="planner-P",
        )
    )
except DelegationScopeMismatch as exc:
    # Correct behavior: mint is refused; planner must re-issue with a scope set
    # that excludes invoices:delete, or drop the prose caveat and own the authority.
    print("REFUSED:", exc)
