# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-policy-as-code-guardrails-from-silently-diverging-at-the-tool-invocation-and-memory-write-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-policy-as-code-guardrails-from-silently-diverging-at-the-tool-invocation-and-memory-write-boundary.warrant.json
# Markdown SHA-256:   6c00aac196838708e65b769635a3922ac865d5b64489a7d70b30329f81504e05
# Code AST SHA-256:   2e39df1cfefd7376943f3ef672c23b3b9999bbaf1e47c62ad842abf7710d5066
# Verified Classes:   ProvenanceEnvelopeError, ProvenanceEnvelope
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import hmac
import time
from dataclasses import dataclass
from typing import Optional


class ProvenanceEnvelopeError(RuntimeError):
    """Raised when a memory-write lacks a valid attested provenance envelope,
    or when the envelope's facts diverge from the tool-invocation decision."""
    pass


@dataclass(frozen=True)
class ProvenanceEnvelope:
    tool_identity: str          # canonical, e.g. "web.fetch"
    canonical_key: str          # normalized trust-tier lookup key
    content_hash: str           # sha256 of fetched content
    principal_at_call: str      # principal id at tool-invocation time
    principal_role_at_call: str
    issued_at: float
    signature: str              # HMAC over the above fields


def _sign(fields: dict, secret: bytes) -> str:
    msg = "|".join(f"{k}={fields[k]}" for k in sorted(fields)).encode()
    return hmac.new(secret, msg, hashlib.sha256).hexdigest()


def issue_envelope(tool_identity: str, content: bytes, principal_id: str,
                   principal_role: str, secret: bytes) -> ProvenanceEnvelope:
    canonical = tool_identity.strip().lower().replace("_", ".")
    fields = {
        "tool_identity": tool_identity,
        "canonical_key": canonical,
        "content_hash": hashlib.sha256(content).hexdigest(),
        "principal_at_call": principal_id,
        "principal_role_at_call": principal_role,
        "issued_at": time.time(),
    }
    return ProvenanceEnvelope(signature=_sign(fields, secret), **fields)


def verify_and_gate(envelope: Optional[ProvenanceEnvelope],
                    write_content: bytes,
                    current_principal_role: str,
                    trust_tier_map: dict,
                    secret: bytes,
                    max_age_seconds: float = 30.0) -> str:
    if envelope is None:
        raise ProvenanceEnvelopeError(
            "memory.write rejected: no provenance envelope; agent-asserted "
            "provenance strings are not attestable facts"
        )

    fields = {
        "tool_identity": envelope.tool_identity,
        "canonical_key": envelope.canonical_key,
        "content_hash": envelope.content_hash,
        "principal_at_call": envelope.principal_at_call,
        "principal_role_at_call": envelope.principal_role_at_call,
        "issued_at": envelope.issued_at,
    }
    expected = _sign(fields, secret)
    if not hmac.compare_digest(expected, envelope.signature):
        raise ProvenanceEnvelopeError(
            "envelope signature invalid; provenance facts were tampered with "
            "between tool-invocation and memory-write boundaries"
        )

    if hashlib.sha256(write_content).hexdigest() != envelope.content_hash:
        raise ProvenanceEnvelopeError(
            "content hash mismatch: written bytes differ from fetched bytes; "
            "agent may have re-serialized untrusted content"
        )

    if time.time() - envelope.issued_at > max_age_seconds:
        raise ProvenanceEnvelopeError(
            "envelope expired; principal state may have changed since issuance"
        )

    if current_principal_role != envelope.principal_role_at_call:
        # Monotonicity: role may only narrow across the two boundaries.
        raise ProvenanceEnvelopeError(
            f"principal role changed between boundaries "
            f"({envelope.principal_role_at_call} -> {current_principal_role}); "
            f"write must be re-evaluated against the narrower role, not silently allowed"
        )

    tier = trust_tier_map.get(envelope.canonical_key)
    if tier is None:
        raise ProvenanceEnvelopeError(
            f"canonical_key {envelope.canonical_key!r} absent from trust-tier map; "
            f"defaulting is forbidden—unmapped provenance is untrusted by construction"
        )
    return tier
