# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-forged-capability-attestation-when-federated-trust-anchors-are-transitively-chained-across-three-or-more-organizations.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-forged-capability-attestation-when-federated-trust-anchors-are-transitively-chained-across-three-or-more-organizations.warrant.json
# Markdown SHA-256:   48cc09375ba572789971b607919819e50ee45f2d8485c1e3067ef6fa8eafb45c
# Code AST SHA-256:   878c3f0c02d3ee66c2e906b9073865613dab6c8528ed3ffaf985c9f3c01b26f1
# Verified Classes:   PolicyProvenanceError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class PolicyProvenanceError(RuntimeError):
    """Raised when a warrant hop re-anchors a policy it did not author
    without a valid policy_delegation from the policy's namespace owner."""
    pass


def verify_policy_provenance(chain: list[dict], federation_members: set[str]) -> None:
    if not chain:
        raise PolicyProvenanceError("empty warrant chain")
    origin = chain[0]
    origin_anchor = origin["anchor"]
    if origin_anchor not in federation_members:
        raise PolicyProvenanceError(f"origin anchor {origin_anchor!r} not in federation")

    for i, hop in enumerate(chain):
        if hop["anchor"] not in federation_members:
            raise PolicyProvenanceError(
                f"hop[{i}] anchor {hop['anchor']!r} not a federation member"
            )
        ref = hop.get("policy_ref")
        if not ref or "/" not in ref:
            raise PolicyProvenanceError(f"hop[{i}] missing well-formed policy_ref")
        namespace_owner = ref.split("/", 1)[0]
        if i == 0:
            if hop["anchor"] != namespace_owner:
                raise PolicyProvenanceError(
                    f"origin hop anchor {hop['anchor']!r} does not own "
                    f"policy namespace {namespace_owner!r}"
                )
            continue
        if hop["anchor"] == namespace_owner:
            continue
        delegations = hop.get("policy_delegation") or []
        ok = any(
            d.get("delegator") == namespace_owner
            and d.get("delegatee") == hop["anchor"]
            and d.get("policy_ref") == ref
            and d.get("signature_verified") is True
            for d in delegations
        )
        if not ok:
            raise PolicyProvenanceError(
                f"hop[{i}] re-anchors policy {ref!r} from {namespace_owner!r} "
                f"to {hop['anchor']!r} without a verified policy_delegation"
            )


def evaluate_warrant(chain: list[dict], federation_members: set[str]) -> dict:
    # Provenance check MUST run before any constraint table is loaded.
    verify_policy_provenance(chain, federation_members)
    return {"admitted": True, "policy_ref": chain[-1]["policy_ref"]}
