# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-signed-capability-manifest-the-schema-signature-runtime-conformance-gap-in-skill-injection-resistant-tool-registration.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-signed-capability-manifest-the-schema-signature-runtime-conformance-gap-in-skill-injection-resistant-tool-registration.warrant.json
# Markdown SHA-256:   d59acc77c6b13ba673cf6d855852c8d6c07f627221409511aca4ade7eb64bc38
# Code AST SHA-256:   95b0436934be4f9441920f8e922c866b6a6c30b5e54afa7daae5c28af1cbecba
# Verified Classes:   ManifestAdmissionError, SignedManifest, BehavioralBaseline
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class ManifestAdmissionError(RuntimeError):
    """Raised when a signed manifest fails schema-closure or conformance admission."""


@dataclass
class SignedManifest:
    tool_name: str
    input_schema: dict[str, Any]
    output_schema: dict[str, Any]
    side_effects: list[str]
    signature_valid: bool
    signature_key: str


@dataclass
class BehavioralBaseline:
    argument_key_sets: set[frozenset[str]] = field(default_factory=set)
    result_shape_hashes: set[str] = field(default_factory=set)

    def has_baseline(self) -> bool:
        return len(self.result_shape_hashes) >= 2


def _is_closed(schema: dict[str, Any]) -> bool:
    if schema.get("type") != "object":
        return True
    if schema.get("additionalProperties", True) is not False:
        return False
    for sub in schema.get("properties", {}).values():
        if not _is_closed(sub):
            return False
    return True


def _result_shape_hash(result: Any) -> str:
    def shape(obj: Any) -> Any:
        if isinstance(obj, dict):
            return {k: shape(v) for k, v in sorted(obj.items())}
        if isinstance(obj, list):
            return [shape(obj[0])] if obj else []
        return type(obj).__name__

    return hashlib.sha256(
        json.dumps(shape(result), sort_keys=True).encode()
    ).hexdigest()


def admit_manifest(
    manifest: SignedManifest,
    baseline: BehavioralBaseline | None,
    echoes_into_context: bool,
) -> str:
    if not manifest.signature_valid:
        raise ManifestAdmissionError(
            f"manifest for {manifest.tool_name!r} has invalid signature"
        )

    if not _is_closed(manifest.input_schema) and echoes_into_context:
        raise ManifestAdmissionError(
            f"manifest for {manifest.tool_name!r} declares an open input schema "
            f"(additionalProperties: true) reachable into reasoning context; "
            f"signature is provenance-only and cannot bound the injection surface"
        )

    if "read" not in manifest.side_effects and "write" not in manifest.side_effects:
        raise ManifestAdmissionError(
            f"manifest for {manifest.tool_name!r} declares no enforceable "
            f"side-effect class"
        )

    if baseline is None or not baseline.has_baseline():
        return "QUARANTINE"

    return "ADMIT_WITH_GATE"


def enforce_conformance(
    manifest: SignedManifest,
    baseline: BehavioralBaseline,
    arguments: dict[str, Any],
    result: Any,
) -> None:
    arg_keys = frozenset(arguments.keys())
    declared_keys = frozenset(manifest.input_schema.get("properties", {}).keys())

    if not arg_keys <= declared_keys:
        raise ManifestAdmissionError(
            f"conformance violation on {manifest.tool_name!r}: argument keys "
            f"{sorted(arg_keys - declared_keys)} not in declared schema; "
            f"fail-closed to block first-injection novel-key bypass"
        )

    shape_hash = _result_shape_hash(result)
    if shape_hash not in baseline.result_shape_hashes:
        raise ManifestAdmissionError(
            f"conformance violation on {manifest.tool_name!r}: result shape "
            f"{shape_hash[:12]} drifted from baseline; withheld from context"
        )
