# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-verify-skill-provenance-before-first-invocation-and-why-signature-check-at-load-is-insufficient.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-verify-skill-provenance-before-first-invocation-and-why-signature-check-at-load-is-insufficient.warrant.json
# Markdown SHA-256:   90455ba435d99c17ac0043f358d362560f35cdb139f402191d43dee345d0f376
# Code AST SHA-256:   56d212ce6626dafbf1e01640bf5a019e62ae8351bb51d8954126046a6cd6f01c
# Verified Classes:   ProvenanceEnvelopeViolation, SignedEnvelope, ResolvedContext
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ProvenanceEnvelopeViolation(RuntimeError):
    """Raised when the resolved execution context falls outside the
    publisher's signed behavioral envelope at first invocation."""


@dataclass
class SignedEnvelope:
    manifest_hash: str
    allowed_model_pins: set[str]
    required_fragment_hashes: dict[str, str]  # fragment_name -> sha256
    permitted_external_refs: set[str]


@dataclass
class ResolvedContext:
    manifest_hash: str
    model_identity: str
    rendered_fragments: dict[str, str] = field(default_factory=dict)
    external_refs: set[str] = field(default_factory=set)


def _sha256(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def attest_at_invocation(env: SignedEnvelope, ctx: ResolvedContext) -> str:
    """Re-bind provenance against the *resolved* context, not the declared one.
    Returns the composite attestation digest on success."""
    if ctx.manifest_hash != env.manifest_hash:
        raise ProvenanceEnvelopeViolation(
            f"manifest drifted: {ctx.manifest_hash} != signed {env.manifest_hash}"
        )
    if ctx.model_identity not in env.allowed_model_pins:
        raise ProvenanceEnvelopeViolation(
            f"model alias resolved to {ctx.model_identity!r}, outside signed pins "
            f"{sorted(env.allowed_model_pins)}"
        )
    for name, body in ctx.rendered_fragments.items():
        expected = env.required_fragment_hashes.get(name)
        if expected is None:
            raise ProvenanceEnvelopeViolation(
                f"unsigned fragment injected at invocation: {name!r}"
            )
        if _sha256(body) != expected:
            raise ProvenanceEnvelopeViolation(
                f"fragment {name!r} hash {_sha256(body)} != signed {expected}"
            )
    rogue = ctx.external_refs - env.permitted_external_refs
    if rogue:
        raise ProvenanceEnvelopeViolation(
            f"external refs outside envelope: {sorted(rogue)}"
        )
    composite = "|".join(
        [ctx.manifest_hash, ctx.model_identity]
        + [f"{k}:{_sha256(v)}" for k, v in sorted(ctx.rendered_fragments.items())]
    )
    return _sha256(composite)


def first_invocation(env: SignedEnvelope, ctx: ResolvedContext) -> str:
    # Called at first use, after model alias resolution and prompt rendering.
    return attest_at_invocation(env, ctx)
