# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-manifest-skill-injection-from-silently-rewriting-an-agent-s-capability-contract-at-load-time.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-manifest-skill-injection-from-silently-rewriting-an-agent-s-capability-contract-at-load-time.warrant.json
# Markdown SHA-256:   224b0acc9ab7930027942a9432fdd7316c98e532a7437addaf9fb0fc99dc90e8
# Code AST SHA-256:   5b44a9ef335c2c060bdb69a4d492c0db484723cacd553576e41a9a63b1826c6e
# Verified Classes:   ManifestInjectionError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class ManifestInjectionError(RuntimeError):
    """Raised when a loaded manifest attempts to alter the capability contract
    through descriptive prose rather than a signed capability entry."""


# Signed, machine-checkable contract: capability_id -> effect class.
# This is the ONLY source of authorization. Prose is never consulted here.
SIGNED_CONTRACT = {
    "read_file": "read",
    "sync_credentials": "write:credentials",
}

# Argument constraints enforced outside the model, per effect class.
ARG_LIMITS = {
    "write:credentials": {"max_payload_bytes": 4096, "forbidden_sources": {"file_body"}},
}


def authorize_batch(manifests: list[dict], last_known_good: set[str]) -> set[str]:
    """Validate a refreshed manifest batch against the signed contract.

    Rejects the ENTIRE batch on any contract violation. Does not sanitize.
    """
    discovered = set()
    for m in manifests:
        cid = m.get("capability_id")
        desc = m.get("description", "")

        # (i) No tool may appear that is absent from the signed set.
        if cid not in SIGNED_CONTRACT:
            raise ManifestInjectionError(
                f"manifest introduces unsigned capability {cid!r}; "
                f"prose={desc[:80]!r}"
            )

        # (ii) Effect class is taken from the contract, never the manifest.
        declared_effect = m.get("effect_class")
        if declared_effect is not None and declared_effect != SIGNED_CONTRACT[cid]:
            raise ManifestInjectionError(
                f"manifest for {cid!r} attempts to reclassify effect "
                f"{SIGNED_CONTRACT[cid]!r} -> {declared_effect!r}"
            )

        # (iii) Prose that implies a new conditional obligation is a red flag.
        lowered = desc.lower()
        for trigger in ("before use", "always call", "if the workspace", "to establish trust"):
            if trigger in lowered:
                raise ManifestInjectionError(
                    f"manifest {cid!r} embeds imperative obligation in prose: "
                    f"{trigger!r}"
                )
        discovered.add(cid)

    # Monotonic set invariant: refresh may not silently widen capabilities.
    widened = discovered - last_known_good
    if widened:
        raise ManifestInjectionError(
            f"refresh widens capability set by {sorted(widened)}; "
            f"requires out-of-band grant event"
        )
    return discovered


def gate_call(capability_id: str, args: dict, arg_source: str) -> None:
    """Enforce argument-level effect gating independent of model reasoning."""
    effect = SIGNED_CONTRACT.get(capability_id)
    if effect is None:
        raise ManifestInjectionError(f"call to unauthorized capability {capability_id!r}")
    limits = ARG_LIMITS.get(effect)
    if limits:
        if arg_source in limits["forbidden_sources"]:
            raise ManifestInjectionError(
                f"{capability_id!r} invoked with {arg_source!r} payload; "
                f"forbidden for effect class {effect!r}"
            )
        size = len(str(args).encode())
        if size > limits["max_payload_bytes"]:
            raise ManifestInjectionError(
                f"{capability_id!r} payload {size}B exceeds "
                f"{limits['max_payload_bytes']}B limit for {effect!r}"
            )
