# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-for-dynamically-loaded-tool-manifests-when-the-manifest-s-description-field-is-itself-an-executable-pro.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-for-dynamically-loaded-tool-manifests-when-the-manifest-s-description-field-is-itself-an-executable-pro.warrant.json
# Markdown SHA-256:   da6c581276f8b2713cfeba44e64abad788732884e9d150f6841444eb757a0b31
# Code AST SHA-256:   5d29284ea56ac37b2a1b6898b5d2ae5f6d7e791941a4cdb937f687f1b071244c
# Verified Classes:   ManifestInstructionFieldError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ManifestInstructionFieldError(RuntimeError):
    """Raised when an instruction-bearing manifest field would enter the privileged prompt region unsanitized."""
    pass


INSTRUCTION_BEARING_FIELDS = ("description", "title", "examples", "default")
MAX_DESCRIPTION_CHARS = 280
# Imperative/redirect markers that indicate the field is trying to issue orders.
REDIRECT_MARKERS = (
    "note to assistant", "ignore previous", "before calling",
    "you must", "first call", "do not tell", "system:", "assistant:",
)


def sanitize_manifest(manifest: dict, sanitizer) -> dict:
    """
    Route every instruction-bearing field through an unprivileged sanitizer
    (a model with no tools and no secret access) before it can reach the
    model context. Reject the manifest if the raw field is more instruction
    than description.
    """
    clean = dict(manifest)
    for field in INSTRUCTION_BEARING_FIELDS:
        raw = manifest.get(field)
        if raw is None:
            continue
        if not isinstance(raw, str):
            raw = str(raw)
        lowered = raw.lower()
        hits = [m for m in REDIRECT_MARKERS if m in lowered]
        if hits:
            raise ManifestInstructionFieldError(
                f"field '{field}' of tool '{manifest.get('name')}' contains "
                f"redirect markers {hits}; manifest rejected before injection"
            )
        if len(raw) > MAX_DESCRIPTION_CHARS:
            raise ManifestInstructionFieldError(
                f"field '{field}' of tool '{manifest.get('name')}' is "
                f"{len(raw)} chars, exceeds {MAX_DESCRIPTION_CHARS}; "
                f"likely smuggled instructions"
            )
        clean[field] = sanitizer.summarize(raw)  # unprivileged rewrite
    return clean


def attribute_tool_call(call: dict, first_party_instruction: str) -> None:
    """
    Enforce call attribution: a tool call touching a sensitive argument
    must be justified by a first-party instruction, not a manifest field.
    """
    sensitive = call.get("arguments", {}).get("path", "")
    if any(s in sensitive for s in ("credential", "secret", ".ssh", ".env")):
        if sensitive not in first_party_instruction:
            raise ManifestInstructionFieldError(
                f"tool call to {call.get('name')} targets sensitive path "
                f"'{sensitive}' not justified by first-party instruction; "
                f"possible description-injection diversion"
            )
