# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-manifest-declared-capability-from-silently-exceeding-the-capability-the-loader-actually-authorized-in-dynamically-loaded-agen.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-manifest-declared-capability-from-silently-exceeding-the-capability-the-loader-actually-authorized-in-dynamically-loaded-agen.warrant.json
# Markdown SHA-256:   60d4065d77f16cb92678126bc08e70a8a5378239aeff37c4255de3e769ac2886
# Code AST SHA-256:   5071f81d1b6f9e34f1d190ba2a03dbde0b11e85d4b54c0acf8029eccaa87fa6c
# Verified Classes:   CapabilityProjectionError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class CapabilityProjectionError(RuntimeError):
    """Raised when the model-facing capability view diverges from the enforced scope set."""
    pass


def build_model_facing_catalog(manifest: dict, enforced_scopes: frozenset[str]) -> dict:
    declared = frozenset(manifest.get("schema", {}).get("methods", []))
    # The model may only see what the dispatcher will actually honor.
    visible = declared & enforced_scopes
    if declared - enforced_scopes:
        # A manifest declaring more than enforcement allows is a divergence,
        # not a warning: the model would reason over a world the runtime rejects.
        raise CapabilityProjectionError(
            f"manifest declares {sorted(declared - enforced_scopes)} "
            f"but enforcement permits only {sorted(enforced_scopes)}"
        )
    description = manifest.get("description", "")
    if _contains_imperative(description):
        raise CapabilityProjectionError(
            "manifest description contains imperative tool-call syntax; "
            "refusing to inject into model prompt"
        )
    return {"name": manifest["name"], "methods": sorted(visible), "description": _strip_imperatives(description)}


def dispatch(method: str, declared: frozenset[str], enforced: frozenset[str], handler_map: dict):
    if method not in declared:
        # No prefix fallback. Unknown method is a hard reject, not a best-effort route.
        raise CapabilityProjectionError(f"method {method!r} absent from declared schema")
    if method not in enforced:
        raise CapabilityProjectionError(f"method {method!r} not in enforced scope set")
    handler = handler_map.get(method)
    if handler is None:
        raise CapabilityProjectionError(f"no handler bound for authorized method {method!r}")
    return handler()


def _contains_imperative(text: str) -> bool:
    markers = ("call ", "invoke ", "before use", "you must", "execute ")
    low = text.lower()
    return any(m in low for m in markers)


def _strip_imperatives(text: str) -> str:
    return text.replace("Before use,", "").strip()
