# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-a-signed-tool-invocation-receipt-chain-when-an-intermediate-agent-re-signs-a-delegated-prompt-without-preserving-the-ori.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-a-signed-tool-invocation-receipt-chain-when-an-intermediate-agent-re-signs-a-delegated-prompt-without-preserving-the-ori.warrant.json
# Markdown SHA-256:   4ceebc452bc8286be308b73ac8ff435a07ca5cdc77886a73c6f412305b3df790
# Code AST SHA-256:   998d8ae696dff266e95a09da0a816001be079c9a589f43d32dca953b9e9cce5f
# Verified Classes:   ProvenanceScopeDriftError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ProvenanceScopeDriftError(RuntimeError):
    """Raised when a receipt's nonce scope is not a valid narrowing of its parent's scope,
    or when a prompt rewrite holds scope constant without a signed preservation attestation."""
    pass


def verify_receipt_chain(chain):
    """
    chain: list of receipts ordered root -> leaf.
    Each receipt: dict with keys
      prompt_hash, tool, args_hash, nonce_scope (frozenset), parent_receipt_hash,
      signature_valid (bool), scope_unchanged_attestation (bool, optional)
    Returns True if the chain is authorization-valid.
    Raises ProvenanceScopeDriftError on the first violation.
    """
    if not chain:
        raise ProvenanceScopeDriftError("empty chain: no provenance root")

    for i, r in enumerate(chain):
        if not r.get("signature_valid", False):
            raise ProvenanceScopeDriftError(
                f"hop {i}: signature invalid for prompt_hash={r.get('prompt_hash')!r}"
            )
        if i == 0:
            continue

        parent = chain[i - 1]
        child_scope = frozenset(r["nonce_scope"])
        parent_scope = frozenset(parent["nonce_scope"])

        # Condition 1: monotonic narrowing. Widening is always fatal.
        if not child_scope.issubset(parent_scope):
            raise ProvenanceScopeDriftError(
                f"hop {i}: scope widened. child={sorted(child_scope)} "
                f"parent={sorted(parent_scope)}"
            )

        # Condition 2: representation identity. If the prompt changed but scope
        # did not narrow, demand an explicit signed preservation attestation.
        prompt_changed = r["prompt_hash"] != parent["prompt_hash"]
        scope_narrowed = child_scope < parent_scope
        if prompt_changed and not scope_narrowed:
            if not r.get("scope_unchanged_attestation", False):
                raise ProvenanceScopeDriftError(
                    f"hop {i}: prompt rewritten (hash {parent['prompt_hash']!r} -> "
                    f"{r['prompt_hash']!r}) with no scope narrowing and no "
                    f"preservation attestation; treating as authorization drift"
                )

        # Condition 3: derivation root. Parent link must resolve to the prior hop.
        if r.get("parent_receipt_hash") != parent.get("prompt_hash") and \
           r.get("parent_receipt_hash") is not None:
            # parent_receipt_hash is expected to be the hash of the parent receipt
            # record; here we assert it is present and stable across the hop.
            if r["parent_receipt_hash"] != parent.get("receipt_hash", parent.get("prompt_hash")):
                raise ProvenanceScopeDriftError(
                    f"hop {i}: parent_receipt_hash does not resolve to prior hop"
                )

    return True
