# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-federated-discovery-registry-entry-when-the-remote-org-s-policy-router-rewrites-the-capability-envelope-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-federated-discovery-registry-entry-when-the-remote-org-s-policy-router-rewrites-the-capability-envelope-mid-handoff.warrant.json
# Markdown SHA-256:   a37421fd646bff7435b9f237f7dca52941e3ab1af9f1b24ead5bd8e5c09fdfbc
# Code AST SHA-256:   87c14fc4dd4631c0d5cbe6a11a4600df4249c96154b9b88343c1b4a34333f202
# Verified Classes:   EnvelopeDivergenceError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class EnvelopeDivergenceError(RuntimeError):
    """Raised when the delivered envelope's hash diverges from the bound registry hash
    without an accompanying policy-rewrite provenance flag."""
    pass


def verify_handoff_receipt(
    bound_hash: str,
    delivered_hash: str,
    policy_rewrite: bool,
    registry_ttl_valid: bool,
) -> str:
    """
    Reconcile a federated handoff receipt against the bound registry hash.
    Returns one of: 'accept', 'accept_with_audit', 'replan', 'reject_integrity'.
    """
    if delivered_hash == bound_hash:
        if policy_rewrite:
            # Rewrite occurred but hash is stable: audit, do not block.
            return "accept_with_audit"
        return "accept"

    # Hash diverged from the bound value.
    if not registry_ttl_valid:
        # Could be legitimate staleness; must re-discover before binding.
        return "replan"

    if policy_rewrite:
        # Observable, signed rewrite: task scope changed. Re-plan, do not bind.
        return "replan"

    # Divergence with no rewrite flag and a valid TTL: unexplained mutation.
    raise EnvelopeDivergenceError(
        f"delivered envelope hash {delivered_hash!r} diverges from bound "
        f"{bound_hash!r} with no policy_rewrite provenance and a valid registry TTL; "
        f"treating as integrity failure and refusing to bind downstream state"
    )


def bind_result_to_plan(verdict: str, result: dict, plan_state: dict) -> dict:
    if verdict in ("replan",):
        # Do not bind. Return plan unchanged so the caller re-plans against
        # the delivered envelope or escalates for a wider warrant.
        return plan_state
    if verdict == "accept_with_audit":
        plan_state.setdefault("audit_log", []).append(result.get("envelope_hash"))
    plan_state["bound_result"] = result
    return plan_state
