# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-borrow-a-tool-under-a-narrowed-scope-and-still-execute-the-un-narrowed-capability.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-borrow-a-tool-under-a-narrowed-scope-and-still-execute-the-un-narrowed-capability.warrant.json
# Markdown SHA-256:   76edcbb334a607c858a9b18ac9790de6b81dbdc1a1e9add4a1e20f24388b9400
# Code AST SHA-256:   e7e14629b96826a66b81ca648dabcf4ddaf950165f562625c867cde11ece7f4a
# Verified Classes:   ScopeProjectionLaundering, CapabilityDescriptor, ExecutionBinding
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ScopeProjectionLaundering(RuntimeError):
    """Raised when a negotiated narrowed capability is not enforced at dispatch."""
    pass


@dataclass
class CapabilityDescriptor:
    fields: dict            # name -> {"required": bool, "allowed": set|None, "default": any}
    schema_hash: str = ""

    def __post_init__(self):
        raw = repr(sorted(self.fields.items())).encode()
        self.schema_hash = hashlib.sha256(raw).hexdigest()


@dataclass
class ExecutionBinding:
    handler_schema_hash: str
    defaults: dict = field(default_factory=dict)

    def dispatch(self, descriptor: CapabilityDescriptor, call: dict) -> dict:
        # Invariant 1: handler must be bound to the negotiated descriptor.
        if self.handler_schema_hash != descriptor.schema_hash:
            raise ScopeProjectionLaundering(
                f"handler bound to {self.handler_schema_hash[:8]} but "
                f"descriptor is {descriptor.schema_hash[:8]}; dispatch refused"
            )
        resolved = {}
        for name, spec in descriptor.fields.items():
            if name in call:
                val = call[name]
                if spec["allowed"] is not None and val not in spec["allowed"]:
                    raise ScopeProjectionLaundering(
                        f"{name}={val!r} outside negotiated scope {spec['allowed']}"
                    )
                resolved[name] = val
            elif spec["required"]:
                raise ScopeProjectionLaundering(
                    f"required narrowed field {name!r} omitted; no default permitted"
                )
            else:
                default = spec.get("default")
                if spec["allowed"] is not None and default not in spec["allowed"]:
                    # The exact latent bug: dispatcher default escapes the pin.
                    raise ScopeProjectionLaundering(
                        f"default for {name!r} ({default!r}) violates negotiated "
                        f"scope {spec['allowed']}; borrower may not elide this field"
                    )
                resolved[name] = default
        return resolved


def negotiate_and_call(borrower_request: dict) -> dict:
    # Lender narrows region to us-east-1 and max_rows to 100.
    narrowed = CapabilityDescriptor(fields={
        "region":   {"required": False, "allowed": {"us-east-1"}, "default": "us-east-1"},
        "max_rows": {"required": False, "allowed": {100}, "default": 100},
    })
    # Dispatcher registered against the ORIGINAL schema -> hash mismatch.
    original_hash = CapabilityDescriptor(fields={
        "region":   {"required": False, "allowed": None, "default": "*"},
        "max_rows": {"required": False, "allowed": None, "default": 1000},
    }).schema_hash
    binding = ExecutionBinding(handler_schema_hash=original_hash)
    return binding.dispatch(narrowed, borrower_request)


if __name__ == "__main__":
    try:
        negotiate_and_call({"max_rows": 100})  # borrower elides region, trusting the pin
    except ScopeProjectionLaundering as exc:
        print(f"BLOCKED: {exc}")
