# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-dynamically-loaded-agent-skill-or-mcp-tool-manifest-as-untrusted-code-rather-than-as-declarative-configurat.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-dynamically-loaded-agent-skill-or-mcp-tool-manifest-as-untrusted-code-rather-than-as-declarative-configurat.warrant.json
# Markdown SHA-256:   e5a67f98e054444833dcdf66f2d8dadd43eddd7cf8dc78c8d3ee4f8424ef44f6
# Code AST SHA-256:   23c6415c7b74639fb8e1835181346cfe255b353e28d58fabedf2138ab7e2972e
# Verified Classes:   UntrustedManifestError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UntrustedManifestError(RuntimeError):
    """Raised when a dynamically loaded skill or MCP tool manifest
    could influence the model instruction stream or dispatch table
    while originating from outside the runtime trust root."""
    pass


TRUSTED_MANIFEST_ROOTS = (
    "/opt/agent/skills",       # hash-pinned, reviewed at build
    "/opt/agent/mcp_manifests",
)

# Fields that, if present and un-sanitized, grant model-facing authority.
AUTHORITY_FIELDS = ("description", "instructions", "preamble", "default_args")


def admit_manifest(manifest: dict, source_path: str, *, sanitized: bool) -> dict:
    """Gate a manifest before it enters the live toolset.

    Fails closed: any manifest that can influence the model or dispatch
    while coming from an untrusted source is rejected unless explicitly
    sanitized by the operator.
    """
    if not isinstance(manifest, dict):
        raise UntrustedManifestError(f"manifest at {source_path!r} is not a mapping")

    name = manifest.get("name")
    if not name or not isinstance(name, str):
        raise UntrustedManifestError(f"manifest at {source_path!r} lacks a valid name")

    trusted = any(
        source_path.startswith(root.rstrip("/") + "/") for root in TRUSTED_MANIFEST_ROOTS
    )

    has_authority_field = any(field in manifest for field in AUTHORITY_FIELDS)

    if not trusted and has_authority_field and not sanitized:
        # Untrusted manifest carries a model-facing field and was not
        # stripped/namespaced by the operator: this is code, not config.
        raise UntrustedManifestError(
            f"untrusted manifest {name!r} from {source_path!r} exposes "
            f"authority fields {[f for f in AUTHORITY_FIELDS if f in manifest]}; "
            "sanitize or relocate to a trusted root before admission"
        )

    if not trusted:
        # Namespace to prevent dispatch shadowing of trusted tools.
        manifest = dict(manifest)
        manifest["name"] = f"untrusted__{name}"
        for field in AUTHORITY_FIELDS:
            manifest.pop(field, None)

    return manifest
