# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-tool-description-and-agent-card-metadata-as-untrusted-executable-content-rather-than-inert-configuration.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-tool-description-and-agent-card-metadata-as-untrusted-executable-content-rather-than-inert-configuration.warrant.json
# Markdown SHA-256:   e3bb0ba2bacf4eebb97fbf23fd54ff1338a19a4ab5292945feb3ac4dfd283ce2
# Code AST SHA-256:   931d20f26bfac85bb233d29d5433227f9ef41efadbed4d1935eefc781530129d
# Verified Classes:   MetadataAuthorityViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class MetadataAuthorityViolation(RuntimeError):
    """Raised when a tool/agent selection is not authorized by the catalog entry that produced it."""
    pass


def authorize_selection(selection, catalog_entry, policy):
    """
    selection: the model-emitted tool_use / peer-route block.
    catalog_entry: the rendered entry (with nonce) the model was shown this turn.
    policy: capability-confinement policy (allowed target set per entry).
    """
    if selection.nonce != catalog_entry.nonce:
        raise MetadataAuthorityViolation(
            f"selection nonce {selection.nonce!r} does not match presented entry "
            f"{catalog_entry.nonce!r}; description attempted to redirect to a different capability"
        )
    if selection.target not in policy.allowed_targets(catalog_entry):
        raise MetadataAuthorityViolation(
            f"entry for {catalog_entry.tool!r} authorized targets "
            f"{policy.allowed_targets(catalog_entry)!r}, got {selection.target!r}"
        )
    if selection.target != catalog_entry.tool and not policy.explicit_rediscovery(selection):
        raise MetadataAuthorityViolation(
            f"cross-tool redirection {catalog_entry.tool!r} -> {selection.target!r} "
            f"without re-entering discovery; treating description as data-only"
        )
    return selection


def render_catalog(entries, nonce_factory):
    rendered = []
    for entry in entries:
        rendered.append(
            {
                "tool": entry.tool,
                "description": entry.description,  # untrusted prose, fenced at render
                "nonce": nonce_factory(entry),
            }
        )
    return rendered
