# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-manifest-skill-injection-from-surviving-the-trust-boundary-crossing-at-load-time.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-manifest-skill-injection-from-surviving-the-trust-boundary-crossing-at-load-time.warrant.json
# Markdown SHA-256:   47eda7a324d5c7ba85b78c90c4cd1a27d87d92160c358a7fe7c7033f794ac46a
# Code AST SHA-256:   dc28a31c9663e8e3fa6682218133b9edbea73a8dbcb1cb73ea348a31ac827acd
# Verified Classes:   ManifestTrustError, ManifestGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestTrustError(RuntimeError):
    """Raised when a manifest delta crosses the planner trust boundary unsafely."""
    pass


# Fields the planner actually reads and renders into its prompt.
PLANNER_SURFACE_FIELDS = ("name", "description", "when_to_use", "examples", "param_docs")
# Fields the dispatcher validates against.
SCHEMA_SURFACE_FIELDS = ("name", "parameters")


def _hash_surface(manifest: dict, fields: tuple) -> str:
    payload = {k: manifest.get(k) for k in fields}
    canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass
class ManifestGate:
    approved_planner_hash: str
    approved_schema_hash: str
    quarantine: list = field(default_factory=list)

    def admit(self, incoming: dict) -> str:
        planner_h = _hash_surface(incoming, PLANNER_SURFACE_FIELDS)
        schema_h = _hash_surface(incoming, SCHEMA_SURFACE_FIELDS)

        schema_changed = schema_h != self.approved_schema_hash
        planner_changed = planner_h != self.approved_planner_hash

        if planner_changed and not schema_changed:
            # The exact failure mode: description-only edit, schema hash stable.
            self.quarantine.append(incoming.get("name"))
            raise ManifestTrustError(
                f"planner-surface delta with stable schema hash for "
                f"{incoming.get('name')!r}; quarantined pending review"
            )
        if planner_changed and schema_changed:
            self.quarantine.append(incoming.get("name"))
            raise ManifestTrustError(
                f"concurrent planner+schema change for {incoming.get('name')!r}; "
                f"requires explicit dual-hash review"
            )
        return "admitted"


def sync_manifest(gate: ManifestGate, incoming: dict) -> str:
    try:
        return gate.admit(incoming)
    except ManifestTrustError:
        raise
    except Exception as exc:  # noqa: BLE001 - surface anything unexpected
        raise ManifestTrustError(f"unexpected manifest sync failure: {exc}") from exc
