# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-verify-a-skill-s-provenance-before-binding-it-into-its-active-tool-schema-and-why-post-load-validation-cannot-recover-from-regi.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-verify-a-skill-s-provenance-before-binding-it-into-its-active-tool-schema-and-why-post-load-validation-cannot-recover-from-regi.warrant.json
# Markdown SHA-256:   3ce214b392be27b42f0726211d6c94d29930b46d917f8f4f503f616e4a3c68ee
# Code AST SHA-256:   e5b1a1beb254c2127b75f3176b04151b47e21d0de930ca90994cec50ddbe8b7b
# Verified Classes:   SkillProvenanceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SkillProvenanceError(RuntimeError):
    """Raised when a skill manifest cannot be admitted to the trusted channel
    under the startup-pinned trust root and untrusted-channel framing invariant."""


TRUSTED_CHANNEL = "operator_instruction"
QUARANTINE_CHANNEL = "untrusted_skill_data"


def admit_skill(manifest: dict, pinned_trust_root: set[str], startup_root_frozen: bool) -> str:
    """
    Decide which channel a skill description may enter.
    Returns the channel name, or raises SkillProvenanceError if the manifest
    violates the provenance invariant. Fails closed on trust-root mutation.
    """
    if not startup_root_frozen:
        # Trust root changed after startup; refuse to admit anything.
        raise SkillProvenanceError(
            "trust root mutated mid-session; refusing skill admission (fail closed)"
        )

    signer = manifest.get("signer")
    signature_ok = signer in pinned_trust_root and manifest.get("signature_verified", False)

    description = manifest.get("description", "")
    # Prose preconditions that instruct invocation of OTHER skills are the
    # signature of registry-poisoning. A tool contract must declare
    # dependencies structurally, never through description prose.
    prose_precondition = any(
        marker in description.lower()
        for marker in ("you must first call", "before calling this", "first invoke")
    )

    if prose_precondition:
        raise SkillProvenanceError(
            f"skill {manifest.get('name')!r} smuggles an invocation precondition "
            "through description prose; refusing to bind"
        )

    if signature_ok:
        return TRUSTED_CHANNEL

    # Unsigned / untrusted-origin description: admissible only as quarantined data.
    return QUARANTINE_CHANNEL


def bind_skill(manifest: dict, pinned_trust_root: set[str], startup_root_frozen: bool) -> dict:
    channel = admit_skill(manifest, pinned_trust_root, startup_root_frozen)
    return {
        "name": manifest["name"],
        "schema": manifest["schema"],
        "channel": channel,
        "description_authoritative": channel == TRUSTED_CHANNEL,
    }
