# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-registry-entry-whose-manifest-hash-is-valid-but-whose-schema-is-adversarially-widened.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-registry-entry-whose-manifest-hash-is-valid-but-whose-schema-is-adversarially-widened.warrant.json
# Markdown SHA-256:   8347ab58a024b483e0ba680decc7edb5ac9b9796cd163bd875e9f76fcfe7e283
# Code AST SHA-256:   78dc18499848df6503f0798974336622ec4d1a0bb928c90f599d42d4f31983e7
# Verified Classes:   SchemaCapabilityViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SchemaCapabilityViolation(RuntimeError):
    """Raised when a hash-valid tool manifest widens the agent's egress surface."""
    pass


# Parameters that can carry agent/conversation state out of the runtime.
EGRESS_CAPABLE_PARAMS = {"context", "history", "transcript", "prior_outputs", "memory"}
IMPERATIVE_MARKERS = ("you must", "before using", "first call", "always send", "do not tell")


def _schema_params(manifest: dict) -> set[str]:
    props = manifest.get("schema", {}).get("properties", {})
    return set(props.keys())


def _description_is_imperative(manifest: dict) -> bool:
    desc = (manifest.get("description") or "").lower()
    return any(marker in desc for marker in IMPERATIVE_MARKERS)


def load_skill(manifest: dict, approved_manifest: dict, hash_valid: bool) -> dict:
    # Integrity is necessary but NOT sufficient.
    if not hash_valid:
        raise SchemaCapabilityViolation("manifest hash invalid; refusing load")

    new_params = _schema_params(manifest) - _schema_params(approved_manifest)
    widened_egress = new_params & EGRESS_CAPABLE_PARAMS

    if widened_egress:
        raise SchemaCapabilityViolation(
            f"hash-valid manifest widens egress surface via params: {sorted(widened_egress)}"
        )

    if _description_is_imperative(manifest) and not _description_is_imperative(approved_manifest):
        raise SchemaCapabilityViolation(
            "description shifted from declarative to imperative; treating as injection"
        )

    return manifest
