# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-declared-capability-set-after-a-hot-reload-without-re-validating-the-descriptor-s-provenance-ch.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-declared-capability-set-after-a-hot-reload-without-re-validating-the-descriptor-s-provenance-ch.warrant.json
# Markdown SHA-256:   b976ac12c6ccadf1abc216f8cf76c88e47fa48d4a01d7427a7cdd33b94138461
# Code AST SHA-256:   2ed3636131538087b3aa9452de87220d8fbbd0edca7abb38da54778d2a35e3b6
# Verified Classes:   DescriptorProvenanceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json


class DescriptorProvenanceError(RuntimeError):
    """Raised when a hot-reloaded tool descriptor cannot be re-admitted
    through the full provenance gate (signature + full-descriptor hash)."""
    pass


def canonical_hash(descriptor: dict) -> str:
    # Hash EVERY field the planner or policy layer reads, not just schema.
    # If a field is added later, it must be added here or the invariant breaks.
    material = {
        "name": descriptor.get("name"),
        "description": descriptor.get("description"),
        "inputSchema": descriptor.get("inputSchema"),
        "outputSchema": descriptor.get("outputSchema"),
        "capabilities": descriptor.get("capabilities"),
        "annotations": descriptor.get("annotations"),
    }
    blob = json.dumps(material, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def admit_on_reload(
    descriptor: dict,
    admitted: dict,          # tool_id -> {"hash": str, "publisher": str}
    verify_signature,        # (descriptor, publisher) -> bool
    pinned_publishers: set,
) -> dict:
    tool_id = descriptor.get("name")
    publisher = descriptor.get("publisher")

    new_hash = canonical_hash(descriptor)
    prior = admitted.get(tool_id)

    if prior is not None and prior["hash"] == new_hash:
        # Idempotent refresh: bytes identical, safe to reuse cached trust.
        return prior

    # Bytes changed (or first admission). Re-admission required.
    if publisher not in pinned_publishers:
        raise DescriptorProvenanceError(
            f"reload of {tool_id!r}: publisher {publisher!r} not pinned; "
            f"refusing to merge changed descriptor"
        )
    if not verify_signature(descriptor, publisher):
        # Do NOT fall back to cached trust. Halt the reload.
        raise DescriptorProvenanceError(
            f"reload of {tool_id!r}: signature verification failed for "
            f"changed descriptor (prior_hash={prior and prior['hash']}, "
            f"new_hash={new_hash}); planner must not see this descriptor"
        )

    # Signature valid: re-admit and surface the planner-visible delta.
    if prior is not None:
        _log_planner_visible_delta(tool_id, prior, descriptor)
    return {"hash": new_hash, "publisher": publisher}


def _log_planner_visible_delta(tool_id, prior, descriptor):
    # Emit description/capability changes before the planner re-reads them.
    print(f"[admission] {tool_id}: descriptor changed and re-signed; "
          f"new description={descriptor.get('description')!r} "
          f"caps={descriptor.get('capabilities')!r}")
