# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-loaded-skill-manifest-as-untrusted-code-before-first-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-loaded-skill-manifest-as-untrusted-code-before-first-invocation.warrant.json
# Markdown SHA-256:   78d2f0df3645611779401e92615290da2d909c64378de6590ca57d2b8c7575f6
# Code AST SHA-256:   8ac4b4f853d5a1e53c966bfd54b9d5c84bae3a7fd484fe70e6b1557310382872
# Verified Classes:   ManifestTrustError, TrustTier, SkillManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field
from enum import Enum

class ManifestTrustError(RuntimeError):
    """Raised when a manifest is promoted or routed above its trust tier."""
    pass

class TrustTier(Enum):
    UNTRUSTED = "untrusted"      # parsed, prose quarantined, no witness
    WITNESSED = "witnessed"      # body ran under sandbox, schema matched
    TRUSTED = "trusted"          # operator-cleared, prose may enter instruction tier

@dataclass
class SkillManifest:
    name: str
    prose_fields: dict          # description, when_to_use, examples
    declared_params: list
    tier: TrustTier = TrustTier.UNTRUSTED
    cross_skill_refs: list = field(default_factory=list)

_FOREIGN_TOOL = re.compile(r"\b(?:call|prefer|use|route to)\s+([a-z_][a-z0-9_]*)", re.I)

def scan_for_steering(manifest: SkillManifest, known_tools: set) -> list:
    refs = []
    for text in manifest.prose_fields.values():
        for match in _FOREIGN_TOOL.finditer(text):
            target = match.group(1)
            if target in known_tools and target != manifest.name:
                refs.append(target)
    manifest.cross_skill_refs = refs
    return refs

def admit_to_selection(manifest: SkillManifest, known_tools: set) -> None:
    """Gate: manifest may enter the model's tool-selection context only if clean."""
    if manifest.tier is TrustTier.UNTRUSTED:
        refs = scan_for_steering(manifest, known_tools)
        if refs:
            raise ManifestTrustError(
                f"skill {manifest.name!r} steers toward foreign tools {refs}; "
                f"withheld from selection pending review"
            )
    # prose must be delivered as quoted data, never instruction-tier
    return

def dispatch(tool_name: str, input_class: str, local_allowlist: set) -> str:
    """Deterministic routing gate independent of model tool choice."""
    if input_class == "secret" and tool_name not in local_allowlist:
        raise ManifestTrustError(
            f"RoutingDenied: secret-class input may not route to non-local tool {tool_name!r}"
        )
    return tool_name

def promote_after_witness(manifest: SkillManifest, ran_clean: bool, schema_ok: bool) -> TrustTier:
    if not (ran_clean and schema_ok):
        raise ManifestTrustError(
            f"skill {manifest.name!r} cannot be promoted: no valid execution witness"
        )
    manifest.tier = TrustTier.WITNESSED
    return manifest.tier
