# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-tool-manifest-it-just-loaded-manifest-time-skill-injection-and-the-pre-dispatch-capability-diff.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-tool-manifest-it-just-loaded-manifest-time-skill-injection-and-the-pre-dispatch-capability-diff.warrant.json
# Markdown SHA-256:   08beb6dbd6dd49d06c3a0c216a9720b1d98a57c5678fe3840827c6f0750eec79
# Code AST SHA-256:   d594594f42291578d181cd9d5af470b043f895b8e33238a8ca45d14e2bd35fb5
# Verified Classes:   ManifestTrustError, Manifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ManifestTrustError(RuntimeError):
    """Raised when a schema-valid manifest fails a trust gate at load time."""


SENSITIVE_TOOLS = {"config", "read_file", "http_get", "exec"}
SENSITIVE_ARG_CLASSES = {"token", "path", "url", "env"}


@dataclass
class Manifest:
    tool_name: str
    tenant: str
    description: str
    examples: list = field(default_factory=list)
    schema_valid: bool = True

    def descriptor_hash(self) -> str:
        blob = (self.tool_name + self.description + repr(self.examples)).encode()
        return hashlib.sha256(blob).hexdigest()[:16]


def gate_provenance(m: Manifest, trust_root: str) -> None:
    if m.tenant != trust_root:
        # untrusted free text must not reach planner context as instruction
        raise ManifestTrustError(
            f"untrusted tenant {m.tenant!r} for {m.tool_name!r}; "
            f"descriptor prose must be downgraded to data-only"
        )


def gate_effect_diff(m: Manifest, baseline_tools: set) -> None:
    # redirect injection: no new tool, but prose steers an existing sensitive tool
    referenced = {t for t in SENSITIVE_TOOLS if t in m.description}
    if referenced and m.tool_name not in baseline_tools:
        raise ManifestTrustError(
            f"redirect injection: {m.tool_name!r} references sensitive "
            f"tools {sorted(referenced)} without introducing them"
        )


def gate_example_taint(m: Manifest) -> None:
    for ex in m.examples:
        blob = repr(ex).lower()
        if any(k in blob for k in SENSITIVE_ARG_CLASSES):
            raise ManifestTrustError(
                f"example-taint in {m.tool_name!r}: example demonstrates "
                f"secret-shaped argument passing"
            )


def bind_manifest(m: Manifest, baseline_tools: set, trust_root: str) -> Manifest:
    if not m.schema_valid:
        raise ManifestTrustError(f"{m.tool_name!r} failed schema validation")
    try:
        gate_provenance(m, trust_root)
        gate_effect_diff(m, baseline_tools)
        gate_example_taint(m)
    except ManifestTrustError as e:
        # fail closed: keep prior toolset, log rejection with descriptor hash
        raise ManifestTrustError(f"rejected {m.descriptor_hash()}: {e}") from e
    return m


def resolve_registry(
    manifests: list, baseline_tools: set, trust_root: str
) -> set:
    bound = set(baseline_tools)
    for m in manifests:
        try:
            bind_manifest(m, baseline_tools, trust_root)
            bound.add(m.tool_name)
        except ManifestTrustError:
            continue  # staleness preferred over novelty
    return bound
