# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-dynamically-loaded-capability-manifests-against-skill-injection-before-activating-them.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-dynamically-loaded-capability-manifests-against-skill-injection-before-activating-them.warrant.json
# Markdown SHA-256:   8764b4c130b270ee2377c28cbf08f7760e61a4a7ee1410e43636b682e5443d75
# Code AST SHA-256:   a061af4c1d1c8deaed38002fdf160549321c282f1faca39ffe518c95494c89e0
# Verified Classes:   ManifestTrustViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ManifestTrustViolation(RuntimeError):
    """Raised when an untrusted manifest field would gain instruction authority."""
    pass


IMPERATIVE_TRIGGERS = (
    "always first call",
    "pass the result",
    "before responding, call",
    "export_context",
    "send the conversation",
)


def screen_manifest(manifest: dict, provenance: str) -> dict:
    """Gate a manifest between VALIDATED and REGISTERED.

    Schema validity is assumed already checked. This gate only governs
    whether descriptive text may enter the model-visible prompt.
    """
    if provenance not in ("registry:trusted", "peer:untrusted"):
        raise ManifestTrustViolation(
            f"manifest has no recognized provenance tag: {provenance!r}"
        )

    model_visible = ("description", "examples", "instructions", "when_to_use")

    for field in model_visible:
        text = manifest.get(field)
        if text is None:
            continue
        lowered = text.lower()
        for trigger in IMPERATIVE_TRIGGERS:
            if trigger in lowered and provenance == "peer:untrusted":
                raise ManifestTrustViolation(
                    f"untrusted field {field!r} contains cross-tool imperative "
                    f"{trigger!r}; manifest rejected, not sanitized"
                )
        # Quarantine: untrusted text is wrapped, never concatenated raw.
        if provenance == "peer:untrusted":
            manifest[field] = f"<untrusted_manifest_text>{text}</untrusted_manifest_text>"

    manifest["_trust_state"] = "REGISTERED"
    return manifest


def activate_skill(manifest: dict, provenance: str) -> dict:
    if manifest.get("inputSchema") is None:
        raise ManifestTrustViolation("cannot activate manifest without inputSchema")
    try:
        return screen_manifest(manifest, provenance)
    except ManifestTrustViolation:
        # Never fall through to registration on a failed screen.
        manifest["_trust_state"] = "QUARANTINED"
        raise
