# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-load-a-skill-manifest-as-trusted-code-when-the-manifest-is-only-data.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-load-a-skill-manifest-as-trusted-code-when-the-manifest-is-only-data.warrant.json
# Markdown SHA-256:   cc6aefa6ed9af919dac223dc6bf5840225dbd604df51bb45202336dc286ca369
# Code AST SHA-256:   de25b4ce05af01b3a2515657d1cb910f7f80e997e60b1e405aa68098bdcecee6
# Verified Classes:   ManifestTrustViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ManifestTrustViolation(RuntimeError):
    """Raised when a model-consumed manifest field bypasses the sanitizer gate."""


PARSER_CONSUMED = {"name", "version", "inputSchema", "endpoint", "signature"}
MODEL_CONSUMED = {"description", "examples", "whenToUse"}
IMPERATIVE_MARKERS = ("first ", "you must", "read ", "include ", "send ", "call ")


def sanitize_model_field(field: str, value: str, max_len: int = 512) -> str:
    low = value.lower()
    for marker in IMPERATIVE_MARKERS:
        if marker in low:
            raise ManifestTrustViolation(
                f"field '{field}' contains imperative construction '{marker.strip()}'; "
                "refusing to merge into model context"
            )
    if len(value) > max_len:
        raise ManifestTrustViolation(
            f"field '{field}' exceeds {max_len} chars; truncation not permitted on model-consumed fields"
        )
    return f"<untrusted-skill-data field='{field}'>{value}</untrusted-skill-data>"


def merge_manifest(manifest: dict) -> dict:
    merged = {}
    for field, value in manifest.items():
        if field in PARSER_CONSUMED:
            merged[field] = value
        elif field in MODEL_CONSUMED:
            if not isinstance(value, str):
                raise ManifestTrustViolation(f"model-consumed field '{field}' must be a string")
            merged[field] = sanitize_model_field(field, value)
        else:
            raise ManifestTrustViolation(
                f"unclassified manifest field '{field}': cannot route to parser or model safely"
            )
    return merged
