# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-tool-manifest-whose-declared-schema-is-structurally-valid-but-semantically-self-authorizing.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-tool-manifest-whose-declared-schema-is-structurally-valid-but-semantically-self-authorizing.warrant.json
# Markdown SHA-256:   ab8b259a05a8a6bb52f42345160483ff238d16fc377f7d7f27ec106a26fd0bdc
# Code AST SHA-256:   eb02d326021ea0913e0542e7ce64f5a1496f4002219dfff8eaf38516fabb1d11
# Verified Classes:   ManifestAuthorityError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ManifestAuthorityError(RuntimeError):
    """Raised when an untrusted manifest field would be promoted into a directive context."""
    pass


DIRECTIVE_BEARING_FIELDS = ("description", "default", "examples", "enum", "name")

# Fields whose content is constrained to a closed, non-instruction-bearing grammar.
CLOSED_GRAMMAR_FIELDS = ("name", "enum")  # name checked against allowlist below


def admit_manifest(manifest: dict, *, source_trusted: bool, trusted_names: set[str]) -> dict:
    """
    Gate a tool manifest at load time.

    Invariant: a field from an untrusted source may not be promoted into a
    directive-bearing context (prompt, routing, default-argument prefill,
    name-shadowing) unless its grammar is closed or the source is trusted.
    Schema validity alone is NOT sufficient.
    """
    if not isinstance(manifest, dict) or "name" not in manifest:
        raise ManifestAuthorityError("manifest missing name; cannot bind")

    name = manifest["name"]
    if not isinstance(name, str) or not name:
        raise ManifestAuthorityError("manifest name must be a non-empty string")

    if not source_trusted:
        # Name-shadowing: refuse to let an untrusted manifest collide with a trusted tool.
        if name in trusted_names:
            raise ManifestAuthorityError(
                f"untrusted manifest attempts to shadow trusted tool {name!r}"
            )

        for field in DIRECTIVE_BEARING_FIELDS:
            if field not in manifest:
                continue
            if field in CLOSED_GRAMMAR_FIELDS:
                # Closed-grammar field: still must not shadow, but content is bounded.
                continue
            # Free-text / open-grammar field from untrusted source: do NOT promote.
            # Quarantine it as inert metadata instead of raising only when the
            # loader would otherwise bind it; here we fail closed on any
            # directive-bearing open field to force explicit provenance upgrade.
            raise ManifestAuthorityError(
                f"untrusted manifest field {field!r} is directive-bearing and "
                f"open-grammar; refusing promotion (quarantine or pin source)"
            )

    # Trusted source or untrusted-but-closed-grammar manifest: admit.
    return manifest


def register_tool(manifest: dict, *, source_trusted: bool, registry: dict[str, dict]) -> None:
    trusted_names = set(registry.keys())
    admitted = admit_manifest(
        manifest, source_trusted=source_trusted, trusted_names=trusted_names
    )
    registry[admitted["name"]] = admitted
