# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-widens-its-own-delegated-scope-through-transitive-sub-delegation-in-aaif-warrant-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-widens-its-own-delegated-scope-through-transitive-sub-delegation-in-aaif-warrant-chains.warrant.json
# Markdown SHA-256:   e5a9677aab664617b882e59af35d7781b4cb5604e672df0099b1c3eac9ee4a34
# Code AST SHA-256:   04a7d87143060687442cc186aa42a5d91756f6e237a384684b2ecd82659337ac
# Verified Classes:   ScopeWideningError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ScopeWideningError(RuntimeError):
    """Raised when a child warrant's instantiated denotation escapes its parent's."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    selector: str                      # e.g. "fs:read:/data/tenant-{tenant_id}/reports/*"
    bindings: dict[str, frozenset]     # attribute -> allowed concrete values
    parent: Optional["Warrant"] = field(default=None, compare=False)


def _placeholders(selector: str) -> set[str]:
    out, i = set(), 0
    while (i := selector.find("{", i)) != -1:
        j = selector.find("}", i)
        out.add(selector[i + 1:j])
        i = j + 1
    return out


def verify_subset(child: Warrant, parent: Warrant) -> None:
    # Clause 1: no template laundering — every placeholder the parent pinned
    # must be pinned in the child too.
    leaked = _placeholders(child.selector) & set(parent.bindings)
    if leaked:
        raise ScopeWideningError(
            f"child {child.subject} carries unresolved placeholders "
            f"{sorted(leaked)} that parent {parent.subject} had pinned"
        )

    # Clause 2: binding-subset — child's allowed values per attribute must be
    # contained in the parent's, for every attribute the child references.
    for attr in _placeholders(child.selector):
        if attr not in child.bindings:
            raise ScopeWideningError(
                f"child references unbound attribute {attr!r}"
            )
        if attr in parent.bindings:
            extra = child.bindings[attr] - parent.bindings[attr]
            if extra:
                raise ScopeWideningError(
                    f"binding widening on {attr!r}: child admits "
                    f"{sorted(extra)} not granted by parent"
                )


def verify_chain(leaf: Warrant) -> None:
    node = leaf
    while node.parent is not None:
        verify_subset(node, node.parent)
        node = node.parent


def resolve_at_use(w: Warrant, attr: str, value: str) -> str:
    # Clause 4: resolution only from pinned bindings, never ambient context.
    allowed = w.bindings.get(attr)
    if allowed is None or value not in allowed:
        raise ScopeWideningError(
            f"ambient resolution of {attr}={value!r} not pinned in warrant "
            f"issued to {w.subject}"
        )
    return w.selector.replace("{" + attr + "}", value)
