# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-re-signed-skill-manifest-mid-session-when-its-capability-warrant-was-minted-against-the-pre-injection-digest.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-re-signed-skill-manifest-mid-session-when-its-capability-warrant-was-minted-against-the-pre-injection-digest.warrant.json
# Markdown SHA-256:   cafad235e4e09c301343f0b2d4c030c7bf6b0da66673970f15009797132060a2
# Code AST SHA-256:   1d66addf9d49f3f983d14fc4d05bc1b28afcaf56155f3cabbc1b58789962a280
# Verified Classes:   ManifestDigestMismatch, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestDigestMismatch(RuntimeError):
    """Raised when a delivered manifest's digest does not cohere with the capability warrant."""
    pass


@dataclass(frozen=True)
class Warrant:
    agent_id: str
    subject_digest: str          # digest of the manifest the warrant was minted over
    projection_version: str      # version of the canonical capability projection
    expires_at: float


def capability_projection(manifest: dict, projection_version: str) -> dict:
    # The projection is the trust boundary: only capability-bearing fields survive.
    # A field omitted here is a field an attacker can mutate without tripping the guard.
    if projection_version != "v3":
        raise ManifestDigestMismatch(
            f"unsupported projection version {projection_version!r}; cannot verify coherence"
        )
    return {
        "skills": sorted(
            (s["name"], tuple(sorted(s.get("scope", []))))
            for s in manifest.get("skills", [])
        ),
    }


def projection_digest(manifest: dict, projection_version: str) -> str:
    proj = capability_projection(manifest, projection_version)
    blob = json.dumps(proj, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def bind_manifest(
    manifest: dict,
    manifest_digest: str,
    signature_ok: bool,
    warrant: Warrant,
    now: float,
) -> dict:
    if not signature_ok:
        raise ManifestDigestMismatch("manifest signature failed; refusing to bind")
    if now >= warrant.expires_at:
        raise ManifestDigestMismatch("warrant expired; refusing to bind")

    # The load-bearing conjunct the incident trace was missing:
    if manifest_digest != warrant.subject_digest:
        # Byte-level mismatch. It may still be a benign cosmetic re-sign — but only
        # if the capability projection is provably unchanged under the SAME projection
        # version the warrant was minted against.
        delivered_proj = projection_digest(manifest, warrant.projection_version)
        # The warrant must carry the projection digest it authorized. If it does not,
        # we cannot prove equivalence and must reject.
        authorized_proj = getattr(warrant, "subject_projection_digest", None)
        if authorized_proj is None or delivered_proj != authorized_proj:
            raise ManifestDigestMismatch(
                f"capability projection changed: manifest={manifest_digest[:12]} "
                f"warrant_subject={warrant.subject_digest[:12]} "
                f"delivered_proj={delivered_proj[:12]} "
                f"authorized_proj={str(authorized_proj)[:12]} — re-warrant required"
            )

    # Bind atomically only after coherence is proven.
    return {
        "bound_digest": manifest_digest,
        "skills": [s["name"] for s in manifest.get("skills", [])],
        "provenance_tag": manifest_digest,  # tag episodic records produced under this binding
    }
